简体   繁体   中英

Repost : SQl query to sum-up amounts by month/year

Repost link here

My query is

SELECT MONTH(now()) as m, SUM(total) as grandtotal
FROM tb
group BY YEAR(now()), MONTH(now())

I'm searching how to get total from this year and month, but my grandtotal is sum last year too. For example I have data year 2018 month 8 = 20 and year 2017 month 8 = 40.. it will sum all. so my total going to be 60 not 20.

example sqlfiddle

Use only month in group by - it will give you total sum in month level but if you put year also in group by level then it will show year and month wise totalsum

SELECT MONTH(now()) as m, SUM(total) as grandtotal
FROM tb
group BY MONTH(now())

Based on answer from last time

select year(date) as y, month(date) as m, sum(paid) as p
from table
where year(now()) = year(date) and month(now()) = month(date)
group by year(date), month(date)

Note that if your table definition is different, then the column names may also differ.

You should group by your field's values, not by a constant.

SELECT MONTH(YourDateField) as m, SUM(total) as grandtotal
FROM tb
WHERE YEAR(YourDateField) = YEAR(now())
GROUP BY YEAR(YourDateField), MONTH(YourDateField)

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