简体   繁体   English

SQL - 按日期和年份求和

[英]SQL - SUM BY DATE and YEAR

I'm trying to write a live report.我正在尝试写一份现场报告。 As of now, I am able to sum by month MONTH(DATEADD(MM, -1, GETDATE())) but it's adding all sales in November.截至目前,我可以按月MONTH(DATEADD(MM, -1, GETDATE()))但它会增加 11 月的所有销售额。 I need it to sum based on month and year from current date -1 month.我需要它根据当前日期-1 个月的月份和年份求和。

PS I cannot do a where clause of YEAR(GETDATE()) = 2021 as this needs to be a live report just in case we want to make it run the past 14 months. PS 我不能做YEAR(GETDATE()) = 2021的 where 子句,因为这需要是一个实时报告,以防我们想让它在过去 14 个月内运行。

Thank you.谢谢你。

SQL SQL

SUM(
CASE
WHEN COALESCE(month(CONVERT(date,CONVERT(varchar(10),salesdwec.shipdate,120),101)), 0) = month(dateadd(mm, -1,getdate())) THEN
  salesdwec.orderquantity
  ELSE 0
END) AS 'PIROIR_MONTH'

If you are working on SQL-Server, then this should work.如果您正在使用 SQL-Server,那么这应该可以工作。

SELECT YEAR(salesdwec.shipdate) 'Year',MONTH(salesdwec.shipdate) 'Month',SUM(salesdwec.orderquantity)
FROM salesdwec
WHERE DATEDIFF(MONTH,salesdwec.shipdate,GETDATE()) = 1
GROUP BY YEAR(salesdwec.shipdate) ,MONTH(salesdwec.shipdate)

As Dale K already mentioned, it would have helped if you provided some sample data.正如Dale K已经提到的,如果您提供一些示例数据会有所帮助。

EDIT:编辑:

The query will output the Month and Year column along with order quantity.查询将 output MonthYear列以及订单数量。 In case you need only order quantity, you can use this one.如果您只需要订购数量,您可以使用这个。

SELECT SUM(salesdwec.orderquantity)
FROM salesdwec
WHERE DATEDIFF(MONTH,salesdwec.shipdate,GETDATE()) = 1

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

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