0
這個問題與我以前的問題類似,但我不知道找到解決方案,因爲我沒有使用聯合。如何訂購樞軸?
我有這個疑問
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')
DECLARE @Pivot_Columns AS VARCHAR(MAX),
@select_Columns VARCHAR(max)
SELECT @Pivot_Columns = Stuff((SELECT DISTINCT ',' + Quotename(Item) FROM #SampleData FOR xml path('')), 1, 1, '')
SELECT @select_Columns = Stuff((SELECT DISTINCT ',Sum(' + Quotename(Item) + ') as '+Quotename(Item) FROM #SampleData FOR xml path('')), 1, 1, '')
DECLARE @SQL AS VARCHAR(MAX)
SET @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,
case when grouping(location) = 1 and grouping(name) = 0 then CONVERT(varchar(10), COUNT(Distinct location))
when grouping(location) = 1 and grouping(name) = 1 then CONVERT(varchar(10), COUNT(Distinct location))
else Location end Location,
'+ @select_Columns + '
FROM
(
SELECT name, location, item
FROM #SampleData
) as PivotData
PIVOT
(
count(item)
for item IN ('
+ @Pivot_Columns + ')
) AS PivotResult
group by name,location with rollup
'
EXEC(@SQL)
,結果是這樣的:
如何訂購我的查詢看起來是這樣的?如果世界上沒有我的位置的計數我的查詢提前做工精細
我需要的解決方案來解決這個問題,謝謝!
我不這麼認爲,因爲我有以下日期合計合計很多在我的表的底部。 –
好吧,那麼將刪除我的答案 –