sql - Column is invalid in the select list due to it is not contained in either an aggregate function or the GROUP BY clause -
i'm trying order count each month each year, found there several related functions helpful.
first datepart(m, orderdate), datepart(y, orderdate), wrote code follows:
select datepart(q, orderdate) q , datepart(year, orderdate) y, count(*) count orders group datepart(q, orderdate), datepart(y, orderdate);
but has error: column 'orders.orderdate' invalid in select list because not contained in either aggregate function or group clause.
then, tried use month(dateorder), , year(dateorder) , code follows:
select month(orderdate) m , year(orderdate) y, count(*) count orders group month(orderdate),year(orderdate);
the result of above code shows success.
my question why first code has error second code correct? thanks!
because in select have used datepart(year, orderdate)
searching year part, , in group have datepart(y, orderdate)
- y not short year stand dayofyear
https://docs.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql
short year yy
query work :
select datepart(q, orderdate) q , datepart(year, orderdate) y, count(*) count orders group datepart(q, orderdate), datepart(yy, orderdate);
you can see in demo - using yy
give 2017 today, using y
give 230 - it's 230th day in year
Comments
Post a Comment