利用Oracle SQL实现附近数据的合并合并

ozxc1zmp  于 2023-10-16  发布在  Oracle
关注(0)|答案(1)|浏览(122)

我想询问以下场景的Oracle SQL语法:包含订单数量和装运日期列的表。数据如下所示:

Qty shipment_date
10  9/20
8   9/19
3   9/18
5   9/16
2   9/13

为了最大限度地降低运输成本,我想将发货日期相差不超过2天的合并行合并。你能给我提供这个SQL查询吗?谢谢
预期结果应该如下所示:

Qty shipment_date
2   9/13
8   9/18
18  9/20
emeijp43

emeijp431#

在Oracle 12中,您可以使用MATCH_RECOGNIZE进行逐行模式匹配:

SELECT *
FROM   table_name
MATCH_RECOGNIZE(
  ORDER BY shipment_date
  MEASURES
    SUM(qty) AS qty,
    LAST(shipment_date) AS shipment_date
  PATTERN (first_day within_two_days*)
  DEFINE
    within_two_days AS shipment_date <= FIRST(shipment_date) + INTERVAL '2' DAY
)

其中,对于样本数据:

CREATE TABLE table_name (Qty, shipment_date) AS
SELECT 10, DATE '2023-09-20' FROM DUAL UNION ALL
SELECT  8, DATE '2023-09-19' FROM DUAL UNION ALL
SELECT  3, DATE '2023-09-18' FROM DUAL UNION ALL
SELECT  5, DATE '2023-09-16' FROM DUAL UNION ALL
SELECT  2, DATE '2023-09-13' FROM DUAL;

输出:
| 数量|装运日期|
| --|--|
| 2 |2023-09-13 00:00:00|
| 8 |2023-09-18 00:00:00|
| 18 |2023-09-20 00:00:00:00|
fiddle

相关问题