[英]How to get previous 6 months data, group by each month starting with current month in oracle sql?
This is my table:(DATE is in TIMESTAMP datatype...here i mentioned in DATE)这是我的表:(DATE 在 TIMESTAMP 数据类型中……我在 DATE 中提到过)
DATE(DD/MM/YYYY) VALUE
10/05/2020 3
20/05/2020 7
08/04/2020 12
10/04/2020 28
15/03/2020 13
08/02/2020 12
10/01/2020 28
15/12/2019 13
21/12/2019 18
12/11/2019 17
I want to get我想得到
MONTH TOTAL
05/2020 10
04/2020 40
03/2020 13
02/2020 12
01/2020 28
12/2019 31
I should get only till DEC ie 6 mnths from today.....Thanks in advance!!!!我应该只到 12 月,即从今天起 6 个月......提前谢谢!!!!
A little bit of WHERE
and GROUP BY
:一点
WHERE
和GROUP BY
:
SQL> with test (datum, value) as
2 -- sample data
3 (select timestamp '2020-05-10 00:00:00.000', 3 from dual union all
4 select timestamp '2020-05-20 00:00:00.000', 7 from dual union all
5 select timestamp '2020-04-08 00:00:00.000', 12 from dual union all
6 select timestamp '2020-04-10 00:00:00.000', 28 from dual union all
7 select timestamp '2020-03-15 00:00:00.000', 13 from dual union all
8 select timestamp '2020-02-08 00:00:00.000', 12 from dual union all
9 select timestamp '2020-01-10 00:00:00.000', 28 from dual union all
10 select timestamp '2019-12-15 00:00:00.000', 13 from dual union all
11 select timestamp '2019-12-21 00:00:00.000', 18 from dual union all
12 select timestamp '2019-11-12 00:00:00.000', 17 from dual
13 )
14 -- query you need
15 select to_char(datum, 'yyyy/mm') month,
16 sum(value) total
17 from test
18 where datum >= add_months(trunc(sysdate), -6)
19 group by to_char(datum, 'yyyy/mm')
20 order by month desc;
MONTH TOTAL
------- ----------
2020/05 10
2020/04 40
2020/03 13
2020/02 12
2020/01 28
2019/12 31
6 rows selected.
SQL>
Try the following尝试以下
select
to_char(date, 'MM-YYYY') as months,
sum(value) as total
from myTable
where date > SYSDATE - INTERVAL '6' MONTH
group by
to_char(date, 'MM-YYYY')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.