简体   繁体   中英

Invalid column name error when adding to Group By

I have this in my Select statement and need to add to my GROUP BY

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

When I add the column mQuarter to the Group by I get an error:

Msg 207, Level 16, State 1, Line 27
Invalid column name 'mQuarter'

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))

* Edit *

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'

Use parentheses. However, this can get simplified by getting rid of some of the casts:

( datename(year, getdate()) +
  datename(quarter, getdate()) +
  'Q'
) as mQuarter

datename() is a handy function, because it returns a string rather than a number. The only time you have to be careful is with month , because the month name is returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM