Invalid column name error when adding to Group By

Solution 1:

If you look at Documentation for SELECT statement, you'll see that the GROUP BY evaluated before the SELECT statement, so any columns that you alias in the SELECT do no exist in GROUP BY. What you need to do is GROUP BY the whole thing:

GROUP BY cast(year(getdate()) as nvarchar(4)) +
         cast(DATEPART(QUARTER,getdate()) as nvarchar(1))

Solution 2:

Since you aren't referencing any of the columns in your tables, you don't need to include mQuarter in your GROUP BY clause. If you remove it, you shouldn't see an error; however, without seeing the rest of your query, I'm not sure it will return the result you're looking for. It will just return 20183Q in every row.

Select statements really begin processing at the FROM clause, and end with the SELECT portion of the statement. Meaning the query is read starting at FROM, then GROUP BY, then WHERE... and SELECT is read last. This means that GROUP BY can only reference columns that exist in your FROM clause. Thus, you get the error message 'Msg 207, Level 16, State 1, Line 27 Invalid column name 'mQuarter', because 'mQuarter' doesn't exist until your SELECT statement. So essentially, you have to reproduce your 'mQuarter' column in the GROUP BY as well to get it to work.

GROUP BY cast(year(getdate()) as nvarchar(4))+cast(DATEPART(QUARTER,getdate()) as nvarchar(1))+'Q'