sql中MAX的简单问题

时间:2011-06-08 20:04:40

标签: sql sql-server-2005

我的表格有行:

ID          CountryCode Status
----------- ----------- -----------
2           PL          1
3           PL          2
4           EN          1
5           EN          1

并通过查询

    SELECT [CountryCode]
      ,MAX([Status])
  FROM [TestTable]
  GROUP BY CountryCode,Status

我想得到:

CountryCode Status
----------- -----------
PL          2
EN          1

但我明白了:

CountryCode Status
----------- -----------
EN          1
PL          1
PL          2

此查询有什么问题?

祝你好运

修改

好吧,Thanx为manz答案,但我没有添加部分查询,即:

Having Status != 3

所以我认为我必须在组中使用状态:/

创建和填充表格的脚本:

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
            )

4 个答案:

答案 0 :(得分:5)

您需要按状态删除该组。 group by为CountryCode 状态的每个唯一组合返回一个新行,这不是您想要的。

您可以添加where子句以排除您不想在查询中考虑的行。

尝试:

SELECT [CountryCode]
      ,MAX([Status])
  FROM [TestTable]
  WHERE status <> 3
  GROUP BY CountryCode

答案 1 :(得分:2)

只需通过以下方式从群组中删除状态:

   SELECT [CountryCode]
      ,MAX([Status])
  FROM [TestTable]
  GROUP BY CountryCode

答案 2 :(得分:0)

当您添加group by status时,它会在国家/地区代码中执行其他分组。然后你的MAX选择国家代码的最大值。从分组中删除status

答案 3 :(得分:0)

不要按状态分组。试试这个:

SELECT [CountryCode]
      ,MAX([Status])
  FROM [TestTable]
  GROUP BY CountryCode
相关问题