问题是,我想在表格中显示一列的月份,计数和平均值,但是当我尝试按月分组时,我一直收到错误。
这是代码:
SELECT MONTH(ContractDate) AS Q,
DATENAME(month, ContractDate) AS M,
COUNT(ContractDate) AS C, SUM(ContractPrice) AS S
FROM dashboard
WHERE YEAR(ContractDate) = $year
AND ContractDate IS NOT NULL
AND ContractPrice IS NOT NULL
GROUP BY MONTH(ContractDate)
但这会导致错误:
[Microsoft][SQL Server Native Client 10.0][SQL Server]
Column 'dashboard.ContractDate' is invalid in the select
list because it is not contained in either an aggregate
function or the GROUP BY clause.
但是如果我从群组中删除了MONTH()
......它运行正常..但我需要将它们按月分组,否则我会得到同一个月的多个不算一个。
再次对不起,我做了搜索,并且有很多答案,但就像我说我是菜鸟,他们并没有真正帮助我,因为我不明白为什么会这样。
答案 0 :(得分:5)
您必须在GROUP BY
中拥有所有不是聚合的列。将DATENAME
列添加到GROUP BY
或将其从查询中删除。
GROUP BY MONTH(ContractDate) AS Q, DATENAME(month, ContractDate)
答案 1 :(得分:0)
删除DATENAME(month, ContractDate) AS M
后尝试执行查询。我想这是导致这个问题的原因。您正在执行GROUP BY MONTH(ContractDate)
,但也尝试使用不在ContractDate
列表中的GROUP BY
。