这是我使用pivot函数获取所需输出的表格
SELECT *FROM ( SELECT
t3.State_Name,left(datename(month,t1.Invoice_Date),3)as [month],t1.Qty
from t1 join t3 on t1.Area_code=t3.Area_code) as PIVOT
(
SUM(qty)
FOR [month] IN ( apr,
may, jun, jul, aug, sep))AS pvt
//for the above table my output is
State_Name apr may jun jul aug sep
--------- ----- ----- ----- ---- ---- -----
Andhra 7 NULL NULL 6 12 16
Telangana 9 1 13 NULL NULL 13
TN NULL 4 NULL 6 10 19
我需要在此表格中再添一列,列出这几个月的总数 所以我通过将上面的表插入new..but使用上面的表,但我需要输出而不插入新表
select state_name,apr,may,jun,jul,aug,sep,coalesce(apr,0) + coalesce(may,0)
+ coalesce(jun,0) + coalesce(jul,0) + coalesce(aug,0) + coalesce(sep,0) as
"total"from #temp8
//output
state_name apr may jun jul aug sep total
---------- ----- ---- ---- ---- ----- ---- ------
Andhra 7 NULL NULL 6 12 16 41
Telangana 9 1 13 NULL NULL 13 36
TN NULL 4 NULL 6 10 19 39
示例数据
2017-06-12 100 Telangana
2017-07-18 101 Andhra
2017-06-16 102 Telangana
2017-04-24 103 Andhra
2017-02-23 104 Andhra
2017-03-17 105 Andhra
2017-05-08 106 Telangana
2017-04-01 107 Telangana
2017-05-29 108 TN
2017-07-19 109 TN
2017-08-17 110 TN
2017-08-13 111 TN
2017-09-12 112 TN
2017-09-02 113 TN
2017-10-13 114 Andhra
2017-08-11 115 Andhra
2017-09-13 116 Telangana
2017-10-10 117 Telangana
2017-10-13 118 Telangana
2017-11-06 119 TN
2017-09-18 120 Andhra
2017-09-11 115 Andhra
答案 0 :(得分:0)
获取样本数据:
DECLARE @DataSource TABLE
(
[DateAdded] DATE
,[value] INT
,[name] VARCHAR(12)
);
INSERT INTO @DataSource ([DateAdded], [value], [name])
VALUES ('2017-06-12', '100', 'Telangana')
,('2017-07-18', '101', 'Andhra')
,('2017-06-16', '102', 'Telangana')
,('2017-04-24', '103', 'Andhra')
,('2017-02-23', '104', 'Andhra')
,('2017-03-17', '105', 'Andhra')
,('2017-05-08', '106', 'Telangana')
,('2017-04-01', '107', 'Telangana')
,('2017-05-29', '108', 'TN')
,('2017-07-19', '109', 'TN')
,('2017-08-17', '110', 'TN')
,('2017-08-13', '111', 'TN')
,('2017-09-12', '112', 'TN')
,('2017-09-02', '113', 'TN')
,('2017-10-13', '114', 'Andhra')
,('2017-08-11', '115', 'Andhra')
,('2017-09-13', '116', 'Telangana')
,('2017-10-10', '117', 'Telangana')
,('2017-10-13', '118', 'Telangana')
,('2017-11-06', '119', 'TN')
,('2017-09-18', '120', 'Andhra')
,('2017-09-11', '115', 'Andhra');
SELECT [name]
,[Apr], [Aug], [Feb], [Jul], [Mar], [Oct], [Sep], [Jun], [May], [Nov]
,[Total]
FROM
(
SELECT [name]
,COALESCE(LEFT(DATENAME(MONTH, [DateAdded]), 3), 'Total') AS [Month]
,SUM([value]) [value]
FROM @DataSource
GROUP BY GROUPING SETS
(
([name], DATENAME(MONTH, [DateAdded]))
,[name]
)
) PVT
PIVOT
(
SUM([value]) FOR [Month] IN ([Apr], [Aug], [Feb], [Jul], [Mar], [Oct], [Sep], [Total], [Jun], [May], [Nov])
) PVT;
查询给我们: