2017-07-04 76 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。 –