Oracle sql查询每月汇总数据

时间:2017-12-06 23:31:33

标签: sql oracle

假设我已经从oktober中选择了数据,直到像这样的

enter image description here

我希望每个月都能获得购买客户的总和(okt-des) 我想要的结果如下表

enter image description here

我已经知道如何获得几个月的最后一天了但是我在SQL中没有想法查询以获得我需要的结果

2 个答案:

答案 0 :(得分:2)

这样做的一种方法 - 如果您只需要这三个月的数据 - 是使用条件聚合:

select   name,
         sum(case when dt >= date '2017-10-01' and dt < date '2017-11-01'
                  then buying end) as oktober,
         sum(case when dt >= date '2017-11-01' and dt < date '2017-12-01'
                  then buying end) as november,
         sum(case when dt >= date '2017-12-01' and dt < date '2018-01-01'
                  then buying end) as desember
from     YOUR_TABLE
where    dt >= date '2017-10-01' and dt < date '2018-01-01'
group by name
;

请注意date是一个Oracle关键字,不应该用作列名;我将其更改为dtYOUR_TABLE应该是您的实际表名。

答案 1 :(得分:1)

试试这个

 DESC TABLE_NAME
        NAME    VARCHAR2(20 BYTE)
        BUYING  NUMBER
        BUYING_DATE DATE

    select * from
    (
    select name,buying,RTRIM(to_char(buying_Date,'Month')) dd
    from
    TABLE_NAME
    )
    PIVOT
    (
    SUM(buying)
    for dd IN ('October','November','December')
    );
相关问题