如何找到列的总和,例如。 'PlanTotal'按另一列的日期或月份,例如。 'PlanStartDate'在过去六个月内?
我已经达到了这个目标,但不知道如何将总和分成几天或几个月。
SELECT SUM(PlanTotal) as PlanTotal
FROM TEST.dbo.Plans
WHERE DATEDIFF(MONTH, cast(cast(PlanStartDate as varchar(8)) as datetime), GETDATE()) <= 6
由于
.....
我用过
SELECT SUM(PlanTotal) as PlanTotal,PlanStartDate
FROM TEST.dbo.Plans
WHERE DATEDIFF(MONTH, cast(cast(PlanStartDate as varchar(8)) as datetime), GETDATE()) <= 6
GROUP BY PlanStartDate
ORDER BY PlanStartDate
这会按个人日显示Plan Total和PlanStartDate,但我似乎仍然无法在每个月进行分组。
如果我这样做:
SELECT SUM(PlanTotal) as PlanTotal,MONTH(PlanStartDate)
FROM TEST.dbo.Plans
WHERE DATEDIFF(MONTH, cast(cast(PlanStartDate as varchar(8)) as datetime), GETDATE()) <= 6
GROUP BY MONTH(PlanStartDate)
ORDER BY PlanStartDate
使用月份组,它只会抛出错误;
Column "TEST.dbo.Plans.PlanStartDate" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
我该如何纠正?
答案 0 :(得分:1)
以下内容应该有所帮助,但是它不会显示PlanStartDate
列中不存在的日期的任何记录
SELECT SUM(PlanTotal) as PlanTotal
,PlanStartDate
FROM TEST.dbo.Plans
WHERE DATEDIFF(MONTH, cast(cast(PlanStartDate as varchar(8)) as datetime), GETDATE())<= 6
Group By PlanStartDate