答案 0 :(得分:1)
如果您的C2中的值并非总是[MP], [KL], [OL], [IFL]
,那么您可能需要尝试使其动态化。如果您的数据集相对较大,请小心使用CROSS JOIN
:< / p>
示例数据:
IF OBJECT_ID('tempdb..#temp') IS NOT NULL
DROP TABLE #temp;
CREATE TABLE #temp(C1 INT
, C2 VARCHAR(10));
INSERT INTO #temp
VALUES
(1
, 'MP'),
(2
, 'KL'),
(3
, 'OL'),
(3
, 'IFL');
QUERY:
SELECT DISTINCT
C1
, [MP] = CASE
WHEN [MP] = C1 THEN 'TRUE'
ELSE ''
END
, [KL] = CASE
WHEN [KL] = C1 THEN 'TRUE'
ELSE ''
END
, [OL] = CASE
WHEN [OL] = C1 THEN 'TRUE'
ELSE ''
END
, [IFL] = CASE
WHEN [IFL] = C1 THEN 'TRUE'
ELSE ''
END
FROM #temp AS A
CROSS JOIN
(SELECT [MP]
, [KL]
, [OL]
, [IFL]
FROM
(SELECT C1
, C2
FROM #temp) AS SourceTable PIVOT(MAX(C1) FOR C2 IN([MP]
, [KL]
, [OL]
, [IFL])) AS PivotTable) AS B;
结果: