use*_*618 0 sql sql-server-2005
我有表行:
ID CountryCode Status
----------- ----------- -----------
2 PL 1
3 PL 2
4 EN 1
5 EN 1
Run Code Online (Sandbox Code Playgroud)
并通过查询
SELECT [CountryCode]
,MAX([Status])
FROM [TestTable]
GROUP BY CountryCode,Status
Run Code Online (Sandbox Code Playgroud)
我想得到:
CountryCode Status
----------- -----------
PL 2
EN 1
Run Code Online (Sandbox Code Playgroud)
但我得到:
CountryCode Status
----------- -----------
EN 1
PL 1
PL 2
Run Code Online (Sandbox Code Playgroud)
这个查询有什么问题?
最好的祝福
编辑
好吧,Thanx for manz答案,但我没有添加部分查询,这是:
Having Status != 3
Run Code Online (Sandbox Code Playgroud)
所以我认为我必须在组中使用Status:/
用于创建和填充表格的脚本:
USE [DatabaseName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TestTable](
[ID] [int] IDENTITY(1,1) NOT NULL,
[CountryCode] [nvarchar](2) NOT NULL,
[Status] [int] NOT NULL
) ON [PRIMARY]
INSERT INTO dbo.TestTable
( CountryCode, Status )
VALUES ( 'PL', -- CountryCode - nvarchar(2)
1 -- Status - int
)
INSERT INTO dbo.TestTable
( CountryCode, Status )
VALUES ( 'PL', -- CountryCode - nvarchar(2)
2 -- Status - int
)
INSERT INTO dbo.TestTable
( CountryCode, Status )
VALUES ( 'EN', -- CountryCode - nvarchar(2)
1 -- Status - int
)
INSERT INTO dbo.TestTable
( CountryCode, Status )
VALUES ( 'EN', -- CountryCode - nvarchar(2)
1 -- Status - int
)
Run Code Online (Sandbox Code Playgroud)
您需要按状态删除该组.group by表示为CountryCode 和 Status的每个唯一组合返回一个新行,这不是你想要的.
您可以添加where子句以排除您不希望在查询中考虑的行.
尝试:
SELECT [CountryCode]
,MAX([Status])
FROM [TestTable]
WHERE status <> 3
GROUP BY CountryCode
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
57 次 |
| 最近记录: |