我知道之前可能会有人问过,但我真的找不到答案。我有一个名为#TEMP
的临时表,如下所示:
+===============================+=============================+
| NAME | ATTRIBUTE |
+===============================+=============================+
| BadgeType | Permanent |
+-------------------------------+-----------------------------+
| PrimaryLocationInCompany | No |
+-------------------------------+-----------------------------+
| AdminAccessToProductionServer | No |
+-------------------------------+-----------------------------+
| AccessToImportantFIles | No |
+-------------------------------+-----------------------------+
| Waiver_Number | 56987 |
+-------------------------------+-----------------------------+
| Summary | User not much active |
+-------------------------------+-----------------------------+
| TimeStamp | 3/3/2009 |
+-------------------------------+-----------------------------+
| UserID | 86478925 |
+-------------------------------+-----------------------------+
我想要做的是将Name
和Attribute
值转置为行。 Attribute
值可能会有所不同,但Name
值始终是固定的。
结果应如下所示:
+----------+---------------+------------------------------+--------------------------------+-----------------------+--------------------------------------------------------+----------+-----------+
| UserID | BadgeType | PrimaryLocationIntelFacility | adminAccessToProductionServer | AccessToClassifiedData| Info_Sec_Waiver_Number | Summary | TimeStamp |
+----------+---------------+------------------------------+--------------------------------+-----------------------+--------------------------------------------------------+----------+-----------+
| 11313403 | GREEN | No | No | No | This contingent worker is eligible for remote access. | 3/3/2009 | |
+----------+---------------+------------------------------+--------------------------------+-----------------------+--------------------------------------------------------+----------+-----------+
答案 0 :(得分:0)
试试这个
SELECT UserID,BadgeType,PrimaryLocationInCompany,AdminAccessToProductionServer,AccessToImportantFIles,WaiverNumber,Summary,[TimeStamp]
FROM
(
SELECT * FROM #Temp
) p
PIVOT
(
MIN([ATTRIBUTE]) FOR [NAME] IN(BadgeType,PrimaryLocationInCompany,AdminAccessToProductionServer,AccessToImportantFIles,WaiverNumber,Summary,[TimeStamp],UserID)
) T
另请查看以下动态列
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + [NAME]
from #Temp
group by [NAME]
FOR XML PATH(''))
,1,1,'')
set @query = 'SELECT ' + @cols + ' from
(
select * from #Temp
) x
pivot
(
MAX([ATTRIBUTE])
for [NAME] in (' + @cols + ')
) p '
execute(@query)