Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Recupero delle prime 10 righe e somma di tutte le altre nella riga 11

Non hai specificato come stai classificando i primi 10 quindi suppongo che i conteggi più alti siano classificati più in alto?

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