2011-03-24 83 views
3

我試圖做一個SQL語句,給我最高的X記錄,然後所有其他的總和。第一部分是容易...有沒有辦法做一些像SQL NOT top語句?

select top 3 Department, Sum(sales) as TotalSales 
from Sales 
group by Department 

什麼是好的是,如果我工會第二查詢類似...

select NOT top 3 "Others" as Department, Sum(sales) as TotalSales 
from Sales 
group by Department 

...的結果集,看起來像,

Department TotalSales 
----------- ----------- 
Mens Clothes 120.00 
Jewelry  113.00 
Shoes   98.00 
Others  312.00 

有什麼辦法可以在TOP上做NOT操作符的等價操作嗎? (我知道我大概可以創建頂級X的臨時表並使用它,但我更喜歡只是單個SQL語句的解決方案。)

+0

很好的答案生日快樂!我被所有的WITH關鍵字引起了循環,因爲我從來沒有見過它。可悲的是,我堅持使用SQL 2000.如果我知道這是一個因素,我會將它包含在我的問題中。我已經提出了所有合適的答案,因爲他們爲大多數人提供了有效的解決方案。 – 2011-03-24 18:20:07

回答

6
WITH q AS 
     (
     SELECT ROW_NUMBER() OVER (ORDER BY SUM(sales) DESC) rn, 
       CASE 
       WHEN ROW_NUMBER() OVER (ORDER BY SUM(sales) DESC) <= 3 THEN 
         department 
       ELSE 
         'Others' 
       END AS dept, 
       SUM(sales) AS sales 
     FROM sales 
     GROUP BY 
       department 
     ) 
SELECT dept, SUM(sales) 
FROM q 
GROUP BY 
     dept 
ORDER BY 
     MAX(rn) 
+0

+1比我的答案簡單! – 2011-03-24 16:18:44

+1

+1'因爲@Martin喜歡它......但如何設置ORDER BY以使「其他」作爲最後一行結束? – 2011-03-24 16:20:59

+2

@Philip Kelley:按部門順序添加'Dept <>'其他',然後SUM(銷售)結束desc' – Andomar 2011-03-24 16:26:05

1

您可以使用聯合來求和所有其他部門。公共表表達式使得這一點更可讀:

; with Top3Sales as 
     (
     select top 3 Department 
     ,  Sum(sales) as TotalSales 
     from Sales 
     group by 
       Department 
     order by 
       Sum(sales) desc 
     ) 
select Department 
,  TotalSales 
from Top3Sales 
union all 
select 'Other' 
,  SUM(Sales) 
from Sales 
where Department not in (select Department from Top3Sales) 

Example at data.stackexchange.com

3
WITH cte 
    As (SELECT Department, 
       Sum(sales) as TotalSales 
     from Sales 
     group by Department), 
    cte2 
    AS (SELECT *, 
       CASE 
        WHEN ROW_NUMBER() OVER (ORDER BY TotalSales DESC) <= 3 THEN 
        ROW_NUMBER() OVER (ORDER BY TotalSales DESC) 
        ELSE 4 
       END AS Grp 
     FROM cte) 
SELECT MAX(CASE 
      WHEN Grp = 4 THEN 'Others' 
      ELSE Department 
      END)  AS Department, 
     SUM(TotalSales) AS TotalSales 
FROM cte2 
GROUP BY Grp 
ORDER BY Grp 
+0

我總是驚訝馬丁能夠迅速解決這些疑問。如果他在線,我甚至不會試圖回答這些問題......他會比我寫的更好的查詢以5分鐘的時間打敗我。 – 2011-03-24 16:19:44

+0

@mfredrickson - 然後Quassnoi進來一個更簡單的! – 2011-03-24 16:21:14

1
SELECT TOP 3 Department, SUM(Sales) AS TotalSales 
FROM Sales 
GROUP BY Department 
UNION ALL 
SELECT 'Others', SUM(s.Sales) 
FROM Sales s 
WHERE s.Department NOT IN 
     (SELECT Department 
     FROM (SELECT TOP 3 Department, SUM(Sales) 
       FROM Sales 
       GROUP BY Department) D) 
+0

這很好,因爲它可以在早期版本的sql server中工作。 – 2011-03-24 18:15:14

相關問題