sql server如何查找计数行的最大值

时间:2014-08-23 16:39:06

标签: sql-server-2008

我写了以下查询:

DECLARE @countryCode TINYINT
SET @countryCode = 1;

SELECT 
    DivingSite.SiteCode, 
    DATEPART(Month, divingDate) AS 'month number' , 
    COUNT (divingNo) AS 'number of dives in month'
FROM 
    DivingSite
INNER JOIN
    tblDiving ON DivingSite.SiteCode = tblDiving.SiteCode
WHERE 
    DivingSite.countryCode = @countryCode 
    AND divingDate > DATEADD(year, -1, GETDATE())
GROUP BY
    DivingSite.SiteCode, DATEPART(Month, divingDate)

此查询的结果是:

siteCode | month number | number of dives in month
--------------------------------------------------
   107          1                     1
   108          7                     2
   107          8                     2

事情是 - 对于每个siteCode,我只想显示潜水次数最多的月份。所以我想得到结果:

siteCode | month number | number of dives in month
--------------------------------------------------
   108          7                     2
   107          8                     2

我该怎么做?

2 个答案:

答案 0 :(得分:1)

试试这个 - 使用CTE(公用表表达式)和ROW_NUMBER函数"分区"您的数据由siteCode开头,并且从一行开始为每个siteCode编号 - 具有最高潜水次数的RowNum = 1和其他任何其他行号更高的行。

只选择RowNum = 1行,您只能获得潜水次数最多的siteCode个参赛作品。

DECLARE @countryCode TINYINT
SET @countryCode = 1;

;WITH RawData AS
(
    SELECT 
        ds.SiteCode, 
        MonthNumber = DATEPART(Month, divingDate), 
        NumberOfDives = COUNT (divingNo),
        RowNum = ROW_NUMBER() OVER (PARTITION BY ds.SiteCode ORDER BY COUNT(divingNo) DESC)
    FROM 
        dbo.DivingSite ds
    INNER JOIN
        dbo.tblDiving d ON ds.SiteCode = d.SiteCode
    WHERE 
        ds.countryCode = @countryCode 
        AND divingDate > DATEADD(year, -1, GETDATE())
    GROUP BY
        ds.SiteCode, DATEPART(Month, divingDate)
)
SELECT
   SiteCode,
   MonthNumber,
   NumberOfDives
FROM
   RawData
WHERE
   RowNum = 1

答案 1 :(得分:0)

您可以在已有的查询之上创建查询,如下所示:

    select 
        DivingSite.SiteCode, 
        DATEPART(Month, divingDate) as 'month number' , 
        count (divingNo) as 'number of dives in month'
    into #dives
    from DivingSite
        inner join tblDiving on DivingSite.SiteCode = tblDiving.SiteCode
    where 
        DivingSite.countryCode = @countryCode 
        and divingDate > DATEADD(year,-1,GETDATE())
    group by 
        DivingSite.SiteCode, 
        DATEPART(Month, divingDate)


    select d.* from #dives d join 
    (
         SELECT 
             SiteCode, 
             MAX([number of dives in month]) MaxDives
         FROM #dives
         GROUP BY SiteCode
    ) max_dives on max_dives.SiteCode = d.SiteCode 
         and d.[number of dives in month] = max_dives.MaxDives