Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Abrufen der Top-10-Zeilen und Summieren aller anderen in Zeile 11

Sie haben nicht angegeben, wie Sie die Top 10 einordnen, also gehe ich davon aus, dass die höchsten Zählungen höher eingestuft werden?

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