简体   繁体   中英

SQL query: get total values for each month

I have a table that stores, number of fruits sold on each day. Stores number of items sold on particular date.

CREATE TABLE data
(
    code VARCHAR2(50) NOT NULL,
    amount NUMBER(5) NOT NULL,
    DATE  VARCHAR2(50) NOT NULL,
);

Sample data

code  |amount|   date
------+------+------------
aple  |  1   | 01/01/2010
aple  |  2   | 02/02/2010
orange|  3   | 03/03/2010
orange|  4   | 04/04/2010

I need to write a query, to list out, how many apple and orange sold for jan and february?

--total apple for jan
select sum(amount) from mg.drum d where date >='01/01/2010' and cdate < '01/02/2020' and code = 'aple'; 

--total apple for feb
select sum(amount) from mg.drum d where date >='01/02/2010' and cdate < '01/03/2020' and code = 'aple';

--total orange for jan
select sum(amount) from mg.drum d where date >='01/01/2010' and cdate < '01/02/2020' and code = 'orange';

--total orange for feb
select sum(amount) from mg.drum d where date >='01/02/2010' and cdate < '01/03/2020' and code = 'orange';

If I need to calculate for more months, more fruits, its tedious.is there a short query to write?

Can I combine at least for the months into 1 query? So 1 query to get total for each month for 1 fruit?

You can use conditional aggregation such as

SELECT TO_CHAR("date",'MM/YYYY') AS "Month/Year",
       SUM( CASE WHEN code = 'apple' THEN amount END ) AS apple_sold,
       SUM( CASE WHEN code = 'orange' THEN amount END ) AS orange_sold
  FROM data
 WHERE "date" BETWEEN date'2020-01-01' AND date'2020-02-29'
 GROUP BY TO_CHAR("date",'MM/YYYY')

where date is a reserved keyword, cannot be a column name unless quoted.

Demo

select sum(amount), //date.month 
from mg.drum
group by //date.month

//data.month Here you can give experssion which will return month number or name.

select to_char(date_col,'MONTH') as month, code, sum(amount)
from mg.drum
group by to_char(date_col,'MONTH'), code

If you are dealing with months, then you should include the year as well. I would recommend:

SELECT TRUNC(date, 'MON') as yyyymm, code,
       SUM(amount)
FROM t
GROUP BY TRUNC(date, 'MON'), code;

You can add a WHERE clause if you want only some dates or codes.

This will return a separate row for each row that has data. That is pretty close to the results from your four queries -- but this does not return 0 values.

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