检索前10行并将第11行中的所有其他行相加

时间:2010-04-08 14:52:17

标签: sql sql-server-2005

我有以下查询来检索每个国家/地区的用户数量;

SELECT C.CountryID AS CountryID, 
       C.CountryName AS Country, 
       Count(FirstName) AS Origin
FROM Users AS U
INNER JOIN Country AS C ON C.CountryID = U.CountryOfOrgin
GROUP BY CASE C.CountryName, 
              C.CountryID

我需要的是获得前10名然后将所有其他用户排成一行的方法。我知道如何获得前十名,但我仍然坚持让剩下的一排。有一个简单的方法吗?

例如,如果上述查询返回17条记录,则前十条记录显示,剩下的7个国家/地区的用户总和应显示在第11行。在该行11上,countryid为0,国家/地区名称为Others

感谢您的帮助!

2 个答案:

答案 0 :(得分:12)

你没有说明你如何排名前10位,所以我假设最高排名更高?

With TopItems As
    (
    SELECT C.CountryID AS CountryID
            , C.CountryName AS Country
            , Count(FirstName) AS Origin
            , ROW_NUMBER() OVER( ORDER BY Count(FirstName) DESC ) As Num
    FROM Users AS U
        JOIN Country AS C 
            ON C.CountryID = U.CountryOfOrgin
    GROUP BY C.CountryName, C.CountryID
    )
Select CountryId, Country, Origin
From TopItems
Where Num <= 10
Union ALL
Select 0, 'Others', Sum(Origin)
From TopItems
Where Num > 10

答案 1 :(得分:0)

这样的事情:

SELECT
    -- show them
    ROW_NUMBER() OVER (ORDER BY CASE WHEN country_code = 'Others' THEN 1 ELSE 0 END, SUM(n) DESC) AS nr,
    countryID,
    SUM(n)
FROM (
    -- change name for some countries
    SELECT
        CASE WHEN nr >= 11 THEN 'Others' ELSE countryID END AS countryID,
        n
    -- select all countries
    FROM ( 
        SELECT 
                    -- store number to recognize position
            ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) AS nr, 
            countries.countryID,
            COUNT(*) AS n
        FROM
            countries WITH (NOLOCK)
            JOIN
                users WITH (NOLOCK)
            ON
                users.countryID = countries.countryID
        GROUP BY
            countries.countryID
    ) AS x
) AS y
GROUP BY
    countryID
ORDER BY
    -- show Others as last one
    CASE WHEN countryID = 'Others' THEN 1 ELSE 0 END,
    SUM(n) DESC

适合我。