简体   繁体   English

转帖:SQL查询按月/年汇总金额

[英]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.例如,我有 2018 年 8 月 = 20 年和 2017 年 8 月 = 40 年的数据。 so my total going to be 60 not 20.所以我的总数将是 60 而不是 20。

example sqlfiddle示例 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仅在 group by 中使用月份 - 它将为您提供月份级别的总和,但如果您将年份也按级别分组,那么它将显示年份和月份的总和

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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