T-SQL-选择前10名;每组一个

时间:2019-03-03 13:59:08

标签: sql sql-server tsql

新手在这里。

我有具有state_name的公司列表(以及其他现在不相关的数据)。我正在尝试编写一个查询,该查询返回前十名的列表,其中公司仅以state_name和COUNT()出现一次,其中COUNT()最高。

这是我现在的位置:

SELECT TOP 10
    COUNT(*) [# of Complaints]      
    ,state_name
    ,company
FROM dbo.Consumer_Complaints
GROUP BY company,state_name
ORDER BY [# of Complaints] DESC

这将返回以下内容:

# of Complaints state_name company
--------------- ---------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
801             CA         Bank of America
776             CA         Wells Fargo & Company
648             TX         Experian
594             CA         Experian
580             TX         Equifax
566             FL         Bank of America
539             CA         JPMorgan Chase & Co.
518             CA         Equifax
499             FL         Wells Fargo & Company
481             TX         TransUnion Intermediate Holdings, Inc.
       ...

理想情况下,最终效果如下:

 # of Complaints state_name company
 --------------- ---------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    801             CA         Bank of America
    776             CA         Wells Fargo & Company
    648             TX         Experian
    580             TX         Equifax
    539             CA         JPMorgan Chase & Co.
    481             TX         TransUnion Intermediate Holdings, Inc.
   ...

什么是理想的解决方案?

1 个答案:

答案 0 :(得分:1)

使用ROW_NUMBER()和一个子查询:

SELECT TOP 10 c.*
FROM (SELECT COUNT(*) as [# of Complaints],      
             state_name, company
             ROW_NUMBER() OVER (PARTITION BY company ORDER BY COUNT(*) DESC) as seqnum
      FROM dbo.Consumer_Complaints
      GROUP BY company, state_name
     ) c
WHERE seqnum = 1
ORDER BY [# of Complaints] DESC;