oracle 我想得到查询结果Group By和Orderd by Date

b0zn9rqh  于 2023-04-20  发布在  Oracle
关注(0)|答案(2)|浏览(154)

我能用Oracle Query得到如下结果吗?按类型分组,但按日期顺序分隔。日期不能重叠。
[RAW数据]

TYPE    FR_DATE             TO_DATE             INCOME
A       04/14 01:04:15      04/14   22:10:15    100 
A       04/15 03:02:22      04/16   18:10:44    200
B       04/17 05:13:22      04/17   20:11:44    300
B       04/18 01:24:22      04/20   23:13:44    100
A       04/22 05:11:22      04/22   19:25:44    400
A       04/23 02:12:22      04/24   17:43:44    200
B       04/25 02:19:22      04/28   18:32:44    500

[结果]

TYPE    FR_DATE             TO_DATE             INCOME_SUM
A       04/14 01:04:15      04/16 18:10:44      300 
B       04/17 05:13:22      04/20 23:13:44      400 
A       04/22 05:11:22      04/24 17:43:44      600
B       04/25 02:19:22      04/28 18:32:44      500
jutyujz0

jutyujz01#

另一种间隙和孤岛方法是使用match_recognize子句(从12 c开始可用)来执行模式匹配:

select type,
  min(fr_date) as fr_date,
  max(to_date) as to_date,
  sum(income) as income_sum
from your_table
match_recognize (
  order by fr_date
  measures match_number() as mnum
  all rows per match
  pattern (start_type same_type*)
  define same_type as (type = prev(type))
)
group by type, mnum
order by fr_date
类型FR_Date截止日期收入总额
A2019 -04-14 01:04:152023-04-16 18:10:44三百
B2023-04-17 05:13:222023-04-20 23:13:44四百
A2019 -04-22 05:11:222023-04-24 17:43:44六百
B2019 -04-25 02:19:222023-04-28 18:32:44五百

fiddle

nwwlzxa7

nwwlzxa72#

一种选择是将问题视为 * 间隙和岛屿 *,即将某些行分组(岛屿),然后提取所需的数据。
样本数据:

SQL> with test (type, fr_date, to_date, income) as
  2    (select 'A', date '2023-04-14', date '2024-04-14', 100 from dual union all
  3     select 'A', date '2023-04-15', date '2024-04-16', 200 from dual union all
  4     select 'B', date '2023-04-17', date '2024-04-17', 300 from dual union all
  5     select 'B', date '2023-04-18', date '2024-04-20', 100 from dual union all
  6     select 'A', date '2023-04-21', date '2024-04-21', 400 from dual union all
  7     select 'A', date '2023-04-22', date '2024-04-24', 200 from dual union all
  8     select 'B', date '2023-04-25', date '2024-04-28', 500 from dual
  9    ),

查询从这里开始:

10  temp as
 11    (select type, fr_date, to_date, income,
 12       to_number(to_char(fr_date, 'yyyymmdd')) - row_number() over (partition by type order by fr_date) grp
 13     from test
 14    )
 15  select type, min(fr_date) fr_date, max(to_date) to_date, sum(income) income_sum
 16  from temp
 17  group by type, grp
 18  order by fr_date;

TYPE FR_DATE    TO_DATE    INCOME_SUM
---- ---------- ---------- ----------
A    04/14/2023 04/16/2024        300
B    04/17/2023 04/20/2024        400
A    04/21/2023 04/24/2024        600
B    04/25/2023 04/28/2024        500

SQL>

相关问题