简体   繁体   中英

Oracle sql query sum data every month

Let's say i have selected data from oktober until desember like this

在此处输入图片说明

i want to get sum of buying customer in every months (okt-des) The result i want is like table below

在此处输入图片说明

i already know how to get last day of months
but i don't have idea query in SQL to get result like i need

One way to do this - if you just need the data for those three months - is to use conditional aggregation:

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
;

Note that date is an Oracle keyword which should not be used as a column name; I changed it to dt . YOUR_TABLE should be your actual table name.

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM