SQL select invalid because it is not contained in aggregate function
Here's the problem, I want to display the month, count and avg of one column in a table, but I keep getting an error when I try and group it by the month.
This is the code:
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)
But t开发者_开发问答his results in the error:
[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.
But if I removed the MONTH()
from the group by... it works fine.. But I need to have them grouped by month otherwise I get multiple of the same month not counted as one.
Sorry again, I did search and there is HEAPS of answers, but like I said I'm noob and they didn't really help me because I don't understand why this happens.
You have to have all columns that are not aggregates in the GROUP BY
. Either add your DATENAME
column into the GROUP BY
or remove it from the query altogether.
GROUP BY MONTH(ContractDate) AS Q, DATENAME(month, ContractDate)
Try executing your query after removing DATENAME(month, ContractDate) AS M
. I guess this is causing the issue. You are doing a GROUP BY MONTH(ContractDate)
but also trying to use ContractDate
which is not in the GROUP BY
list.
精彩评论