二级Top N SQL服务器

时间:2016-10-06 04:59:47

标签: sql-server group-by top-n

我有一个名称,国家和地位的表格。我希望通过按名称和状态分组获得总数,但只获得前3个国家。

我的表:

+------+---------+--------+
| Name | Country | Status |
+------+---------+--------+
| ABC  | US      | Open   |
| ABC  | US      | Closed |
| ABC  | US      | Open   |
| ABC  | Japan   | Open   |
| ABC  | Japan   | Closed |
| ABC  | China   | Open   |
| ABC  | China   | Closed |
| ABC  | Italy   | Open   |
| DEF  | US      | Open   |
| DEF  | US      | Closed |
| DEF  | Japan   | Open   |
| DEF  | Japan   | Closed |
| DEF  | China   | Open   |
| DEF  | China   | Closed |
| DEF  | China   | Closed |
| DEF  | Italy   | Open   |
+------+---------+--------+

期望的输出:

+------+---------+--------+-------+
| Name | Country | Status | Total |
+------+---------+--------+-------+
| ABC  | US      | Open   |     2 |
| ABC  | US      | Closed |     1 |
| ABC  | Japan   | Open   |     1 |
| ABC  | Japan   | Closed |     1 |
| ABC  | China   | Open   |     1 |
| ABC  | China   | Closed |     1 |
| DEF  | US      | Open   |     1 |
| DEF  | US      | Closed |     1 |
| DEF  | Japan   | Open   |     1 |
| DEF  | Japan   | Closed |     1 |
| DEF  | China   | Open   |     1 |
| DEF  | China   | Closed |     2 |
+------+---------+--------+-------+

我尝试了以下查询,但它没有给我结果我正在寻找。

Select rs.Name, rs.Country, rs.Status, Count(*) as total from (
SELECT Name, Country, Status, Rank() 
          over (Partition BY Name
                ORDER BY Country DESC ) AS Rank
        FROM table1 ) rs WHERE Rank <= 3

6 个答案:

答案 0 :(得分:2)

您可以使用以下查询:

monday

如果是关系,查询会选择与其他国家/地区相比具有“最小”名称的国家/地区。

答案 1 :(得分:1)

您的原始查询肯定是正确的方向(我甚至用它来确定您想要的输出)。但是,您所需的输出是多个聚合的结果,而不仅仅是单个分析函数。在下面的查询中,我首先聚合以获得总计,然后使用排名来保留前3个组。如果是关系,则此查询首先选择按字母顺序排列的国家/地区。

prepare config minimal

答案 2 :(得分:0)

尝试这个..

Select rs.Name, rs.Country, rs.Status, Count(*) as total from rs(
SELECT Name, Country, Status, Count(status) from mytable
    group by status order by Count(status) desc
 ) rs limit 3

答案 3 :(得分:0)

怎么样:

select Top 3 with ties * FROM(
select Name, country, Status
, count(*) as total
, count(*) over (Partition BY Name, Country) as rank
from mytable
group by Name, Country, Status
) i 
order by i.rank desc

答案 4 :(得分:0)

请你试试下面的SQL脚本

Igor

输出如下

enter image description here

答案 5 :(得分:0)

使用以下查询。

;WITH CTE
AS
(
    SELECT NAME,COUNTRY,ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY COUNT(COUNTRY) DESC) ROWNO  FROM TBLCOUNTRY
    GROUP BY NAME,COUNTRY
)
SELECT C.NAME,C.COUNTRY,C.STATUS,COUNT(C.STATUS) TOTAL FROM TBLCOUNTRY C INNER JOIN CTE ON
C.NAME=CTE.NAME AND C.COUNTRY=CTE.COUNTRY AND CTE.ROWNO<=3
GROUP BY C.NAME,C.COUNTRY,C.STATUS
ORDER BY NAME,COUNTRY DESC, STATUS DESC