简体   繁体   English

添加到分组依据时,无效的列名称错误

[英]Invalid column name error when adding to Group By

I have this in my Select statement and need to add to my GROUP BY 我的Select语句中有此内容,需要添加到我的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: 当我将mQuarter列添加到Group by时,出现错误:

Msg 207, Level 16, State 1, Line 27 消息207,第16级,州1,第27行
Invalid column name 'mQuarter' 无效的列名“ 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. 如果查看SELECT语句的文档 ,您会看到GROUP SELECT在SELECT语句之前进行了评估,因此您在SELECT中使用别名的任何列在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. 由于您没有引用表中的任何列,因此无需在GROUP BY子句中包含mQuarter。 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. 它只会在每一行中返回20183Q。


Select statements really begin processing at the FROM clause, and end with the SELECT portion of the statement. Select语句实际上从FROM子句开始处理,并以语句的SELECT部分​​结束。 Meaning the query is read starting at FROM, then GROUP BY, then WHERE... and SELECT is read last. 这意味着查询是从FROM开始读取的,然后是GROUP BY,然后是WHERE ...,最后读取SELECT。 This means that GROUP BY can only reference columns that exist in your FROM clause. 这意味着GROUP BY只能引用FROM子句中存在的列。 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. 因此,您收到错误消息“消息207,级别16,状态1,行27”无效的列名“ mQuarter”,因为直到您的SELECT语句才存在“ mQuarter”。 So essentially, you have to reproduce your 'mQuarter' column in the GROUP BY as well to get it to work. 因此,从本质上讲,您还必须在GROUP BY中重现“ mQuarter”列,以使其正常工作。

GROUP BY cast(year(getdate()) as nvarchar(4))+cast(DATEPART(QUARTER,getdate()) as nvarchar(1))+'Q' 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. datename()是一个方便的函数,因为它返回的是字符串而不是数字。 The only time you have to be careful is with month , because the month name is returned. 您唯一需要注意的是使用month ,因为返回了月份名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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