简体   繁体   中英

How do I sum up values by month in SQL command line?

I want to sum up a variable which is a sum of 2 variables from 2 different tables.

SELECT EXTRACT(MONTH FROM Service.EDate) AS MONTH, 
       SUM(Insurance.Price+Service.Charge) AS PROFIT
FROM 
Service INNER JOIN 
Insurance ON Service.Code=Insurance.Code
WHERE EXTRACT(YEAR FROM Service.EDate)=2018
GROUP BY Service.EDate
ORDER BY Service.EDate;

Expected the answer to be MONTH to have 1 value (1,2,3,4,5 etc. and profit to sum up) but I'm getting MONTH to be separated like profit([1,105],[1,405],[1,320],[2,410],[2,110] etc. having [MONTH,PROFIT])

You seem to want the MONTH in the GROUP BY :

SELECT EXTRACT(MONTH FROM s.EDate) AS MONTH, 
       SUM(i.Price + s.Charge) AS PROFIT
FROM Service s INNER JOIN 
     Insurance i
     ON s.Code = i.Code
WHERE EXTRACT(YEAR FROM s.EDate) = 2018
GROUP BY EXTRACT(MONTH FROM s.EDate)
ORDER BY EXTRACT(MONTH FROM s.EDate);

Note that I added table aliases, so the query is easier to write and to read.

I would recommend using date comparisons rather than EXTRACT() for the WHERE clause:

WHERE s.EDate >= DATE '2018-01-01' AND
      s.EDate < DATE '2019-01-01'

This helps the optimizer, particularly making it possible to use indexes.

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