当Oracle中的字段值更改时增加行号
Posted
技术标签:
【中文标题】当Oracle中的字段值更改时增加行号【英文标题】:increment row number when value of field changes in Oracle 【发布时间】:2013-05-09 22:31:11 【问题描述】:在 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 列,该列在标志值更改时递增。我的结果应该如下所示
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、LEAD 等分析函数来获得上述结果。
【问题讨论】:
【参考方案1】:您可以将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
【讨论】:
以上是关于当Oracle中的字段值更改时增加行号的主要内容,如果未能解决你的问题,请参考以下文章