0
id sem1 sem2 sem3 sem4 sem5 sem6 sem7
1 S O S R null null null
2 O O R R S null null
所需的輸出:
id O R S
1 1 1 2
2 2 2 1
id sem1 sem2 sem3 sem4 sem5 sem6 sem7
1 S O S R null null null
2 O O R R S null null
所需的輸出:
id O R S
1 1 1 2
2 2 2 1
如果你的數據庫支持APPLY/UNPIVOT
運營商然後使用這個
CROSS APPLY
方法
SELECT id,
SUM(CASE WHEN val = 'O' THEN 1 ELSE 0 END) O,
SUM(CASE WHEN val = 'R' THEN 1 ELSE 0 END) R,
SUM(CASE WHEN val = 'S' THEN 1 ELSE 0 END) S
FROM mytable
CROSS apply (VALUES (sem1),
(sem2),
(sem3),
(sem4),
(sem5),
(sem6),
(sem7)) cs(val)
GROUP BY id
UNPIVOT
方法
SELECT id,
SUM(CASE WHEN val = 'O' THEN 1 ELSE 0 END) O,
SUM(CASE WHEN val = 'R' THEN 1 ELSE 0 END) R,
SUM(CASE WHEN val = 'S' THEN 1 ELSE 0 END) S
FROM (SELECT *
FROM mytable) a
UNPIVOT (val
FOR col IN (sem1,
sem2,
sem3,
sem4,
sem5,
sem6,
sem7)) upv
GROUP BY id
我個人偏好CROSS APPLY
方法在UNPIVOT
,因爲它是更具有可讀性。性能明智兩者將是相同的
您可以使用'case when'條件 –
您正在使用哪個'DBMS' –