使用数据透视表或任何其他方法获取行和列的格式?

时间:2018-04-13 20:27:13

标签: sql sql-server

使用数据透视表或任何其他方法获取结果,我需要帮助计算所有12个月的行和列的总计。

以下是样本表及其例外输出。

CREATE TABLE #MonthlyData (ID INT,MonthName VARCHAR(5),Col1 INT,Col2 INT,Col3 INT)

INSERT INTO #MonthlyData
VALUES(1, 'Jan',10,0,9),
(2,'Feb',0,10,1),
(3,'March',1,11,15),
(4,'April',0,20,10),
(5,'May', 0, 10, 1),
(6,'June',0,0,0),
(7,'July',10,10,10),
(8,'Aug',1,1,1),
(9,'Sept',20,10,30),
(10,'Oct',5,4,9),
(11,'Nov',10,10,10),
(12,'Dec',0,0,12)

例外输出:

Month   Col1    Col2    Col3    Total
Jan 10  0   9   19
Feb 0   10  1   11
March   1   11  15  27
April   0   20  10  30
May 0   10  1   11
June    0   0   0   0
July    10  10  10  30
Aug 1   1   1   3
Sept    20  10  30  60
Oct 5   4   9   18
Nov 10  10  10  30
Dec 0   0   12  12
Total   12  12  12  0

1 个答案:

答案 0 :(得分:1)

您可以使用roll up或类似机制。就个人而言,我更喜欢grouping set

select coalesce(monthname, 'total'),  -- the cheap way to do this
       sum(col1) as col1, sum(col2) as col2, sum(col3) as col3,
       sum(col1 + col2 + col3) as total
from #MonthlyData md
group by grouping sets ( (monthname), () )
order by grouping(monthname) desc, min(id);

还有其他方法,例如运行两个单独的查询:

select monthname, col1, col2, col3, (col1 + col2 + col3)
from #MonthlyData
union all
select 'total' as monthname, sum(col1), sum(col2), sum(col3), sum(col1 + col2 + col3)
from #MonthlyData;