我的SQL Server 2008 R2中有以下表格。
Provider ContractID Department StDate EndDate
========================================================
10001 CTR456 IT 1/1/2012 12/1/2014
10001 CT346 Account 4/1/2014 9/9/2014
10002 CT88R01 IT 2/1/2012 2/1/2013
10003 C23TR01 IT 3/2/2012 1/1/2099
10003 C4TR02 Health 3/2/2012 1/1/2099
10003 CT56R03 Security 3/2/2012 1/1/2099
如何使用Pivot或任何其他方法实现以下输出。
Provider Contract1 Dept1 StDt1 EndDt2 Contract2 Dept2 StDate2 EndDt2 Contract3 Dept3 StDate3 EndDt3
=====================================================================================================
10001 CTR456 IT 1/1/12 12/1/14 CT346 Accont 4/1/14 9/9/14 NULL NULL NULL NULL
10002 CT88R01 IT 1/1/12 12/1/14 NULL NULL NULL NULL NULL NULL NULL NULL
10003 C23TR01 IT 1/1/12 12/1/14 C4TR02 Health 3/2/14 1/1/99 CT56R03 Secu 3/2/14 1/1/99
如果有人解决这个问题我很感激。
答案 0 :(得分:0)
试试这个,
DECLARE @sql varchar(max)
DECLARE @colList varchar(max)
--create dynamic list of columns
SELECT @colList =
STUFF
(
(
SELECT + ',' +
quotename(colName + CAST(CAST(REPLACE(ContractID,'CTR','') AS INTEGER) AS VARCHAR))
FROM Tab1
CROSS APPLY
(
SELECT 1 As Ord, 'Contract' ColName UNION ALL
SELECT 2 As Ord, 'Dept' UNION ALL
SELECT 3 As Ord, 'StDt' UNION ALL
SELECT 4 As Ord, 'EndDt'
) v
GROUP BY colName,Ord, CAST(CAST(REPLACE(ContractID,'CTR','') AS INTEGER) AS VARCHAR)
ORDER BY CAST(CAST(REPLACE(ContractID,'CTR','') AS INTEGER) AS VARCHAR), Ord
for xml path(''), type
).value('/','varchar(max)'),1,1,''
)
--unpivot columns into rows and then apply pivot
SET @sql
= '
SELECT Provider, ' + @colList + '
FROM
(
SELECT Provider, ColVal,
colName + CAST(CAST(REPLACE(ContractID,''CTR'','''') AS INTEGER) AS VARCHAR) ColName
FROM Tab1
CROSS APPLY
(
SELECT ContractId As ColVal, ''Contract'' ColName UNION ALL
SELECT Department, ''Dept'' UNION ALL
SELECT CAST(StDate AS VARCHAR), ''StDt'' UNION ALL
SELECT CAST(EndDate AS VARCHAR), ''EndDt''
) v
) A
PIVOT
(
MAX(ColVal) FOR ColName IN (' + @colList + ')
) P1 '
EXEC(@sql)