2016-04-14 47 views

回答

2

如果你的數據庫支持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,因爲它是更具有可讀性。性能明智兩者將是相同的

相關問題