0
user_no day_01 day_02 day_03 day_04 day_05 day_06
44 AA PP PP PP PP AA PP
total(PP)
44 AA PP PP PP PP AA PP 5
user_no day_01 day_02 day_03 day_04 day_05 day_06
44 AA PP PP PP PP AA PP
total(PP)
44 AA PP PP PP PP AA PP 5
你可以在每一天柱使用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
我想,如果列數增加,你需要繼續編寫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
感謝ü工作添Biegeleisen – kumarh