下面是一個基本的PIVOT示例,如果沒有可用的值,則COALESCE顯示'false'。這假定你必須硬編碼列名的顏色名稱。
DECLARE @tUsers TABLE ([uid] INT)
DECLARE @tColors TABLE ([colorid] INT, [colorname] VARCHAR(50))
DECLARE @tColors_User_Detail TABLE ([uid_fk] INT, [colorid_fk] INT)
INSERT @tUsers VALUES (1),(2)
INSERT @tColors VALUES (1,'Blue'),(2,'Red'),(3,'Green')
INSERT @tColors_User_Detail VALUES (1,1),(1,2),(1,3),(2,1)
SELECT
uid,
COALESCE([Red], 'False') AS [Red],
COALESCE([Blue], 'False') AS [Blue],
COALESCE([Green], 'False') AS [Green]
FROM @tUsers U
LEFT OUTER JOIN @tColors_User_Detail CUD
ON CUD.uid_fk = U.uid
LEFT OUTER JOIN @tColors C
ON C.colorid = CUD.colorid_fk
PIVOT (MAX(colorname) FOR colorname IN (
[Red],
[Blue],
[Green]
)) PVT
如果你想讓顏色動態的列,你必須使用動態SQL。
DECLARE @Sql VARCHAR(1000) =
'SELECT uid'
+ (SELECT ', CASE WHEN [' + [colorname] + '] IS NOT NULL THEN ''True'' ELSE ''False'' END AS [' + [colorname] + ']' AS [text()] FROM tColors FOR XML PATH(''))
+ ' FROM tUsers U
LEFT OUTER JOIN tColors_User_Detail CUD
ON CUD.uid_fk = U.uid
LEFT OUTER JOIN tColors C
ON C.colorid = CUD.colorid_fk
PIVOT (MAX(colorname) FOR colorname IN ('
+ SUBSTRING((SELECT ',[' + [colorname] + ']' AS [text()] FROM tColors FOR XML PATH('')), 2, 1000)
+ ')) PVT'
EXEC (@Sql)
你能提供你已經嘗試過的嗎? – Dane
還可以用很少的行對輸入和輸出數據進行採樣以解釋所需的輸出。 – Utsav
Google是PIVOT運營商,或者其他的主要解決方案。這些旨在做你想做的。 –