如何获取前6个月的数据,从oracle sql中的当前月份开始每月分组?

jogvjijk  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(508)

这是我的表:(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

我想得到

MONTH             TOTAL
05/2020            10
04/2020            40
03/2020            13
02/2020            12
01/2020            28
12/2019            31

我只能拿到12月1日,也就是从今天起6个月…..提前谢谢!!!!

new9mtju

new9mtju1#

一点点 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>
ru9i0ody

ru9i0ody2#

请尝试以下操作

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')

相关问题