2013-05-15 71 views
7

在Oracle中爲以下數據編寫查詢時需要幫助。數據按人員和日期字段排序。在Oracle中的字段值更改時增加行號

Person  Day Flag 
    ------  --- ---- 
    person1 day1 Y 
    person1 day2 Y 
    person1 day3 Y 
    person1 day4 N 
    person1 day5 N 
    person1 day6 Y 
    person1 day7 Y 
    person1 day8 Y 

我需要有一個Group_Number列,每當Flag值發生變化時都會增加。我的結果應該如下

Person  Day Flag Group_Number 
    ------  --- ---- ------------ 
    person1 day1 Y 1 
    person1 day2 Y 1 
    person1 day3 Y 1 
    person1 day4 N 2 
    person1 day5 N 2 
    person1 day6 Y 3 
    person1 day7 Y 3 
    person1 day8 Y 3 

我認爲有辦法使用分析功能,如ROW_NUMBER得到上述結果,鉛等

回答

15

您可以組合analytic functionsSUM(用作運行總計)和LAG

SQL> WITH data AS (
    2   SELECT 'person1' person, 'day1' day, 'Y' flag FROM dual 
    3 UNION ALL SELECT 'person1' person, 'day2' day, 'Y' flag FROM dual 
    4 UNION ALL SELECT 'person1' person, 'day3' day, 'Y' flag FROM dual 
    5 UNION ALL SELECT 'person1' person, 'day4' day, 'N' flag FROM dual 
    6 UNION ALL SELECT 'person1' person, 'day5' day, 'N' flag FROM dual 
    7 UNION ALL SELECT 'person1' person, 'day6' day, 'Y' flag FROM dual 
    8 UNION ALL SELECT 'person1' person, 'day7' day, 'Y' flag FROM dual 
    9 UNION ALL SELECT 'person1' person, 'day8' day, 'Y' flag FROM dual 
10 ) 
11 SELECT person, DAY, flag, SUM(gap) over (PARTITION BY person 
12           ORDER BY DAY) grp 
13 FROM (SELECT person, DAY, flag, 
14     CASE WHEN flag = lag(flag) over (PARTITION BY person 
15             ORDER BY DAY) 
16      THEN 0 
17      ELSE 1 
18     END gap 
19   FROM DATA); 

PERSON DAY FLAG  GRP 
------- ---- ---- ---------- 
person1 day1 Y    1 
person1 day2 Y    1 
person1 day3 Y    1 
person1 day4 N    2 
person1 day5 N    2 
person1 day6 Y    3 
person1 day7 Y    3 
person1 day8 Y    3 
+1

+1偉大的邏輯! – TechDo

+0

太棒了。非常感謝你! – pravi

相關問題