[英]Dynamic Pivot Table by Month
我正在嘗試在 SQL 中創建一個動態 pivot 表,該表將基於月份和年份進行報告。 我做了很多研究,並能夠提出以下查詢:
declare @dynamic nvarchar(max),
@column nvarchar(max);
set @column = N'';
select @column += N'' + datename(month,incurdate) +' '+ datename(year,incurdate) + ','
from (select distinct a.incurdate from artable a) as Transpose
select @column = substring(@column,0,len(@column))
set @dynamic = 'select * from
(
select month, incurdate, dolamount
from artable join dolentry on month = period
) b
pivot(sum(dolamount) for incurdate in (' + @column + ')) as PivotTable'
execute sp_executesql @dynamic
我能夠成功打印@column 變量,但是當我嘗試在@dynamic 變量中設置它時會出現問題。 錯誤消息是'消息 102,級別 15,State 1,第 6 行'1990' 附近的語法不正確。 ' 1990 年是第一個樞軸柱的元年。 任何幫助或提示表示贊賞。 謝謝!
您需要在以下代碼中使用QUOTENAME :
select @column += N'' + QUOTENAME(datename(month,incurdate) +' '+ datename(year,incurdate)) + ','
from (select distinct a.incurdate from artable a) as Transpose
為了像這樣獲得 output :
[col01], [col02], [col03], ... , [col04]
正如您從文檔中看到的那樣, PIVOT
語法要求將旋轉列括在方括號中:
SELECT <non-pivoted column>,
[first pivoted column] AS <column name>,
[second pivoted column] AS <column name>,
...
[last pivoted column] AS <column name>
FROM
(<SELECT query that produces the data>)
AS <alias for the source query>
PIVOT
(
<aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
IN ( [first pivoted column], [second pivoted column],
... [last pivoted column])
) AS <alias for the pivot table>
<optional ORDER BY clause>;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.