2016-11-29 51 views
0
user_no day_01 day_02 day_03 day_04 day_05 day_06 
44  AA  PP PP PP  PP  AA  PP 

輸出只有Conut PP和AA

      total(PP) 
44 AA PP PP PP PP AA PP 5 

回答

1

你可以在每一天柱使用CASE表情和做所有天理貨:

SELECT user_no, day_01, day_02, day_03, day_04, day_05, day_06, 
     (CASE WHEN day_01 IN ('PP', 'AA') THEN 1 ELSE 0 END + 
     CASE WHEN day_02 IN ('PP', 'AA') THEN 1 ELSE 0 END + 
     CASE WHEN day_03 IN ('PP', 'AA') THEN 1 ELSE 0 END + 
     CASE WHEN day_04 IN ('PP', 'AA') THEN 1 ELSE 0 END + 
     CASE WHEN day_05 IN ('PP', 'AA') THEN 1 ELSE 0 END + 
     CASE WHEN day_06 IN ('PP', 'AA') THEN 1 ELSE 0 END) AS total 
FROM yourTable 
+0

感謝ü工作添Biegeleisen – kumarh

0

我想,如果列數增加,你需要繼續編寫case語句,查詢可能會變得很大。我會使用Oracle 11g功能UNPIVOT然後計算'P'的出現。請看下圖:

select count(col1) As P_COUNT 
from 
(
WITH tbl (user_no, 
      day_01, 
      day_02, 
      day_03, 
      day_04, 
      day_05, 
      day_06, 
      day_07) 
    AS (SELECT '44', 'AA', 'PP', 'PP', 'PP', 'PP', 'AA', 'PP' FROM DUAL) 
SELECT * 
    FROM tbl 
UNPIVOT ( 
      COL1 
      for COL2 in (user_no, day_01, day_02, day_03, day_04, day_05, day_06, day_07)    
     ) 
    ) z 
    where z.col1 = 'PP' ; 

輸出:

P_COUNT 
---------- 
     5 
相關問題