如何在Oracle SQL Developer中通过YTD值计算MTD和QTD

d6kp6zgx  于 2023-05-16  发布在  Oracle
关注(0)|答案(1)|浏览(143)

I have the following data in the tableI want the following column with MTD of the given data
MTD =截止日期的月份。
如何编写SQL来实现此目的?
尝试使用月函数

fivyi3re

fivyi3re1#

它是sum函数的解析形式。
样本数据:

SQL> with test (datum, district, value) as
  2    (select date '2023-04-14', 'BAGAR',  0 from dual union all
  3     select date '2023-04-15', 'BAGAR',  2 from dual union all
  4     select date '2023-04-16', 'BAGAR', 12 from dual union all
  5     select date '2023-04-17', 'BAGAR',  9 from dual union all
  6     select date '2023-04-18', 'BAGAR',  9 from dual union all
  7     --
  8     select date '2023-05-01', 'BAGAR',  0 from dual union all
  9     select date '2023-05-02', 'BAGAR',  3 from dual union all
 10     select date '2023-05-03', 'BAGAR',  6 from dual
 11    )

查询:

12  select t.*,
 13    sum(value) over (partition by district, trunc(datum, 'mm') order by datum) mtd,
 14    sum(value) over (partition by district, trunc(datum, 'q' ) order by datum) qtd
 15  from test t
 16  order by datum;

DATUM      DISTR      VALUE        MTD        QTD
---------- ----- ---------- ---------- ----------
14-04-2023 BAGAR          0          0          0
15-04-2023 BAGAR          2          2          2
16-04-2023 BAGAR         12         14         14
17-04-2023 BAGAR          9         23         23
18-04-2023 BAGAR          9         32         32
01-05-2023 BAGAR          0          0         32
02-05-2023 BAGAR          3          3         35
03-05-2023 BAGAR          6          9         41

8 rows selected.

SQL>

相关问题