我有以下数据集,其中我想检查一个部分是否有过去3个月的数量,并总结它们。例如,对于部件ABC
,对于01-MAY-23
的月份,vdate列中的最近3个月为01-MAY-23, 01-APR-23, 01-MAR-23
。由于这3个月存在,我想将数量添加为50 + 40 + 30 = 120
。对于DEF
部分则不存在相同的情况,因此该部分不会出现在输出中。data
| PART | VDATE | MONTH | QTY |
|------|-----------|-----------|-----|
| ABC | 01-JAN-23 | 01-MAY-23 | 10 |
| ABC | 01-FEB-23 | 01-MAY-23 | 20 |
| ABC | 01-MAR-23 | 01-MAY-23 | 30 |
| ABC | 01-APR-23 | 01-MAY-23 | 40 |
| ABC | 01-MAY-23 | 01-MAY-23 | 50 |
| ABC | 01-MAR-23 | 01-JUN-23 | 25 |
| ABC | 01-APR-23 | 01-JUN-23 | 35 |
| ABC | 01-MAY-23 | 01-JUN-23 | 45 |
| ABC | 01-JUN-23 | 01-JUN-23 | 55 |
| DEF | 01-APR-23 | 01-MAY-23 | 25 |
| DEF | 01-MAY-23 | 01-MAY-23 | 35 |
Output
| PART | MONTH | QTY |
|------|-----------|-----|
| ABC | 01-MAY-23 | 120 |
| ABC | 01-JUN-23 | 135 |
sql
WITH data AS (
SELECT 'ABC' part, TO_DATE('01-JAN-23') vdate, TO_DATE('01-MAY-23') month, 10 qty FROM dual UNION
SELECT 'ABC' part, TO_DATE('01-FEB-23') vdate, TO_DATE('01-MAY-23') month, 20 qty FROM dual UNION
SELECT 'ABC' part, TO_DATE('01-MAR-23') vdate, TO_DATE('01-MAY-23') month, 30 qty FROM dual UNION
SELECT 'ABC' part, TO_DATE('01-APR-23') vdate, TO_DATE('01-MAY-23') month, 40 qty FROM dual UNION
SELECT 'ABC' part, TO_DATE('01-MAY-23') vdate, TO_DATE('01-MAY-23') month, 50 qty FROM dual UNION
SELECT 'ABC' part, TO_DATE('01-MAR-23') vdate, TO_DATE('01-JUN-23') month, 25 qty FROM dual UNION
SELECT 'ABC' part, TO_DATE('01-APR-23') vdate, TO_DATE('01-JUN-23') month, 35 qty FROM dual UNION
SELECT 'ABC' part, TO_DATE('01-MAY-23') vdate, TO_DATE('01-JUN-23') month, 45 qty FROM dual UNION
SELECT 'ABC' part, TO_DATE('01-JUN-23') vdate, TO_DATE('01-JUN-23') month, 55 qty FROM dual UNION
SELECT 'DEF' part, TO_DATE('01-APR-23') vdate, TO_DATE('01-MAY-23') month, 25 qty FROM dual UNION
SELECT 'DEF' part, TO_DATE('01-MAY-23') vdate, TO_DATE('01-MAY-23') month, 35 qty FROM dual
)
SELECT *
FROM data;
2条答案
按热度按时间svmlkihl1#
你发布的数据
这可能是一种选择:
klsxnrf12#
在Oracle 12中,您可以使用
MATCH_RECOGNIZE
进行逐行模式匹配:其中,对于样本数据:
输出:
| 部分|月|数量|
| --|--|--|
| ABC| 2023-05-01 00:00:00| 120 |
| ABC| 2023-06-01 00:00:00| 135 |
fiddle