SQL: PIVOT的使用
試寫了一下關鍵部分的代碼,記錄下來, 其他的讓小朋友接手處理
範例一:
注意下面的代碼必須使用 YEAR(OrderDate) 的別名 vYear 不能直接使用 YEAR(OrderDate), 應該 YEAR(OrderDate)的值為數值, 如2002,2003等, 程式無法正確進行如果使用別名, 程式會將對應的值處理為 [2002],[2003]等, 程式即可正確進行
SELECT VendorID, [2001],[2002],[2003],[2004],[2005]
FROM
( SELECT VendorID, PurchaseOrderID, YEAR(OrderDate) as vYear
FROM Purchasing.PurchaseOrderHeader ) p
PIVOT
( count(PurchaseOrderID)
FOR vYear IN
( [2001],[2002],[2003],[2004],[2005] )
) AS dd
go
DECLARE @signYear Varchar(4)
DECLARE @signUser Varchar(12)
DECLARE @sql nvarchar(4000)
DECLARE @sqlMonth nvarchar(4000)
SET @signYear = '2009'
SET @signUser = '1578'
SET @sqlMonth= '[' + @signYear + '07],[' + @signYear + '08],[' + @signYear + '09]'
set @sql ='SELECT sign_user, rpt_id, ' + @sqlMonth
set @sql =@sql + ' FROM '
set @sql =@sql + ' (SELECT sign_user, rpt_id, vou_no, left(upd_date,6) AS SignMonth '
set @sql =@sql + ' FROM w_flowsignhist WHERE (sign_user = ' + @signUser + ')) p '
set @sql =@sql + ' PIVOT (count(vou_no) FOR SignMonth IN '
set @sql =@sql + ' (' + @sqlMonth + ')) as pvt'
--PRINT @sql
EXEC sp_executesql @sql
No Response to "SQL: PIVOT的使用"
发表评论