2012-03-15 16 views
2

我有一個組名列和花費的列。 我需要根據組名稱對金額進行分組,然後抓取最高的五位。在那之後,我需要將其餘的組合到它自己的小組中,並花費他們的總金額。這是我現在有抓取前5行並結合其餘SQL Server

SELECT groupName, SUM(amount) AS theAmountSpent 
FROM purchases 
GROUP BY groupName 
ORDER BY theAmountSpent DESC 

這個組和命令他們,但我不知道如何抓住剩餘的組合,他們。任何幫助,將不勝感激。

回答

1

如果我正確理解你,這應該這樣做:

SELECT top 5 groupName, SUM(amount) AS theAmountSpent 
into #tempSpent FROM purchases 
GROUP BY groupName 
ORDER BY theAmountSpent DESC 

Select * from #tempSpent -- get the top 5 

--get sum for the rest 
SELECT SUM(amount) AS theAmountSpent 
FROM purchases 
where groupName not in (select groupName from #tempSpent) 

Drop table #tempSpent 
4

備用CTE的方式使用ROW_NUMBER()(SQL服務器2005 +):

WITH cte AS (
     SELECT ROW_NUMBER() OVER (ORDER BY (SUM(amount)) DESC) AS num, 
     groupName, SUM(amount) AS theAmountSpent 
     FROM purchases 
     GROUP BY groupName 
    ) 
    SELECT groupName, theAmountSpent FROM cte WHERE num BETWEEN 1 AND 5 --top 5 
    UNION ALL 
    SELECT 'Sum rest', SUM(theAmountSpent) FROM cte WHERE num > 5 -- sum of rest 
+0

這當然是更好的方法 – Colin 2012-03-15 22:48:23

0

從Larsts另一個想法代碼:

WITH cte 
    AS 
    (
     SELECT case 
       when ROW_NUMBER() OVER (ORDER BY (SUM(amount)) DESC) <=5 
        then ROW_NUMBER() OVER (ORDER BY (SUM(amount)) DESC) 
        else 6 end AS num 
     ,  groupName                
     ,  SUM(amount) AS theAmountSpent 
     FROM purchases 
     GROUP BY groupName 
    ) 
    SELECT num 
    ,  max(groupName) 
    ,  sum(theAmountSpent) 
    FROM cte 
    group by num