2017-07-04 74 views
0

我已经curret这样的查询创建透视表和计数的项目总按日期在枢轴SQL

CREATE TABLE #SampleData 
 
(
 
    Name varchar(10), 
 
    Location varchar(20), 
 
    Item varchar(10), 
 
    Date varchar(8) 
 
) 
 
INSERT INTO #SampleData 
 
VALUES 
 
('Ron', 'Loc A', 'Pencil', '20170610'), 
 
('Ron', 'Loc A', 'Pencil', '20170611'), 
 
('Ron', 'Loc B', 'Pen', '20170610'), 
 
('Ron', 'Loc B', 'Laptop', '20170611'), 
 
('Tom', 'Loc A', 'Pencil', '20170611'), 
 
('Tom', 'Loc B', 'Pencil', '20170610'), 
 
('Tom', 'Loc B', 'Pen', '20170610'), 
 
('Tom', 'Loc A', 'Pencil', '20170610'), 
 
('Tom', 'Loc A', 'Laptop', '20170610'), 
 
('Tom', 'Loc A', 'Pencil', '20170610') 
 

 
\t DECLARE @Pivot_Columns AS VARCHAR(MAX), 
 
\t \t \t @select_Columns VARCHAR(max) 
 

 
\t SELECT @Pivot_Columns = Stuff((SELECT DISTINCT ',' + Quotename(Item) FROM #SampleData FOR xml path('')), 1, 1, '') 
 
\t SELECT @select_Columns = Stuff((SELECT DISTINCT ',Sum(' + Quotename(Item) + ') as '+Quotename(Item) FROM #SampleData FOR xml path('')), 1, 1, '') 
 

 
\t DECLARE @SQL AS VARCHAR(MAX) 
 

 
\t SET @SQL = 'SELECT case when grouping(location) = 1 and grouping(name) = 0 then ''Total''+ '' '' + name 
 
\t when grouping(location) = 1 and grouping(name) = 1 then ''Total'' 
 
\t else name end Name, location, ' 
 
\t \t \t + @select_Columns + ' 
 
\t FROM 
 
\t (
 
\t \t SELECT name, location, item 
 
\t \t FROM #SampleData 
 

 
\t) as PivotData 
 
\t PIVOT 
 
\t (
 
\t \t count(item) 
 
\t \t for item IN (' 
 
\t \t \t + @Pivot_Columns + ') 
 
\t) AS PivotResult 
 
\t group by name,location with rollup 
 
\t ' 
 

 
\t EXEC(@SQL)

像这样

enter image description here

结果如何在总计下面创建总计日期?

enter image description here

我试图用联盟和它不工作。 如何创建像我的形象总? 在此先感谢。

回答

0

不确定你为什么使用动态SQL。试试这个静态SQL:

SELECT case when grouping(location) = 1 and grouping(name) = 0 then 'Total'+ ' ' + name 
when grouping(location) = 1 and grouping(name) = 1 then 'Total' 
else name end Name, location, Sum([Laptop]) as [Laptop],Sum([Pen]) as [Pen],Sum([Pencil]) as [Pencil] 
FROM 
(
    SELECT name, location, item 
    FROM #SampleData 

) as PivotData 
PIVOT 
(
    count(item) 
    for item IN ([Laptop],[Pen],[Pencil]) 
) AS PivotResult 
group by name,location with rollup 
UNION ALL 
SELECT 'Total' Name, location, Sum([Laptop]) as [Laptop],Sum([Pen]) as [Pen],Sum([Pencil]) as [Pencil] 
FROM 
(
    SELECT [date] as location, item 
    FROM #SampleData 

) as PivotData 
PIVOT 
(
    count(item) 
    for item IN ([Laptop],[Pen],[Pencil]) 
) AS PivotResult 
group by location 
; 
+0

谢谢你,我可以改善你的答案与动态SQL和它的工作。 –

+0

太好了。我总是首先使用静态SQL。 –