2014-09-27 81 views
1

我有表SalesSQL Server 2012在SQL Server中使用RollUp和Group By?

Use tempdb 
Go 

CREATE TABLE Sales (EmpId INT, Yr INT, Sales MONEY) 
INSERT Sales VALUES(1, 2005, 12000) 
INSERT Sales VALUES(1, 2006, 18000) 
INSERT Sales VALUES(1, 2007, 25000) 
INSERT Sales VALUES(2, 2005, 15000) 
INSERT Sales VALUES(2, 2006, 6000) 
INSERT Sales VALUES(3, 2006, 20000) 
INSERT Sales VALUES(3, 2007, 24000) 

我想創造這個結果的報告:

/* 

EmpId------ Yr----- SUM(Sales) BY EmpId, Yr---------- SUM(Sales) BY EmpId ----------SUM(Sales) 

1   2005  12000.00       12000.00      12000.00 
1   2006  18000.00       30000.00      30000.00 
1   2007  25000.00       55000.00      55000.00 
1   NULL          55000.00      55000.00 
2   2005  15000.00       15000.00      70000.00 
2   2006  6000.00       21000.00      76000.00 
2   NULL          21000.00      76000.00 
3   2006  20000.00       20000.00      96000.00 
3   2007  24000.00       44000.00      120000.00 
3   NULL          44000.00      120000.00 
NULL  NULL                  120000.00 
*/ 

我寫這樣的查詢:

SELECT EmpId, Yr, SUM(Sales) AS Sales 
FROM Sales 
GROUP BY EmpId, Yr WITH ROLLUP 

我怎樣才能改變我的查詢以獲得更多列,例如abauve。

+0

你真的需要在其年NULL行?另外,你在使用什麼版本的SQL-Server? – Alireza 2014-09-28 14:56:05

回答

3

在SQL Server 2012+中,您可以使用窗口函數進行累計和。下面基本上你想要做什麼:

SELECT EmpId, Yr, SUM(Sales) AS Sales, 
     SUM(case when Yr is not null then SUM(Sales) end) OVER 
       (PARTITION BY EmpId 
       Order By (case when Yr is null then 0 else 1 end) desc, Yr 
       ), 
     SUM(case when yr is not null then SUM(SALES) end) OVER 
       (Order by EmpId, (case when Yr is null then 0 else 1 end) desc, Yr) 
FROM Sales 
GROUP BY EmpId, Yr WITH ROLLUP 
ORDER BY (case when EmpId is null then 0 else 1 end) desc, empid, 
     (case when Yr is null then 0 else 1 end) desc, yr; 

這是棘手的,因爲rollup和窗口功能之間的相互作用需要小心。

Here是SQL小提琴。

編輯:

要解決的最後一排的最後一個單元格,可以添加一個case聲明:

SELECT EmpId, Yr, SUM(Sales) AS Sales, 
     SUM(case when Yr is not null then SUM(Sales) end) OVER 
       (PARTITION BY EmpId 
       Order By (case when Yr is null then 0 else 1 end) desc, Yr 
       ), 
     (case when yr is null and empid is null 
      then sum(case when yr is not null and empid is not null then sum(sales) end) over() 
      else SUM(case when yr is not null then SUM(SALES) end) OVER 
         (Order by EmpId, (case when Yr is null then 0 else 1 end) desc, Yr) 
     end) 
FROM Sales 
GROUP BY EmpId, Yr WITH ROLLUP 
ORDER BY (case when EmpId is null then 0 else 1 end) desc, empid, 
     (case when Yr is null then 0 else 1 end) desc, yr; 
+0

Merci但你的結果不正確! @Gordon Linoff – 2014-09-27 17:35:12

+1

@ArdalanShahgholi。 。 。出於某種原因,我以爲你想在最後一列的捲起行中使用NULL值。 – 2014-09-27 19:54:22

+0

@GordonLinoff:在最後一行和最後一列的角落,我想SUM(銷售),現在是空?! – 2014-09-27 20:36:02