在groupby子句中包含用户定义的列是不正确的? [英] Is including the user defined columns in groupby clause is incorrect ?

查看:57
本文介绍了在groupby子句中包含用户定义的列是不正确的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

请帮我详细说明Group By Clause。我试图在我的Group By子句中使用一个额外的(用户定义的col),该子句不存在Group by中的原始列,但是它的结果再次出现错误:( !!



我尝试了什么:



查询:

Hi All
Please help me in clarifying about the Group By Clause a little bit more.I tried to use an additional (User defined col) in my Group By clause, which is not present as original column in the Group by, However its ending up with error again:(!!

What I have tried:

The Query:

select CustName,Count(CustName),PurchaseDate,DATENAME(dw,PurchaseDate) as Day from [CustmrSrc] where Day = 'Monday' and Day ='Tuesday' and  Day='Wednesday' and Day='Thursday'and Day='Friday' Group By CustName, PurchaseDate ,Day





错误: -



Error:-

Msg 207, Level 16, State 1, Line 1
Invalid column name 'Day'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Day'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Day'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Day'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Day'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Day'.





问候



Regards

推荐答案

您可以在WHERE和GROUP BY子句中包含用户定义的列,但必须使用完整声明而不是名称。

应用于您的示例,这将给出:

You can include a user-defined column in your WHERE and GROUP BY clauses, but you have to use the full declaration instead of the name.
Applied to your example, this would give:
SELECT
  CustName
 ,Count(CustName)
 ,PurchaseDate
 ,DATENAME(dw,PurchaseDate) as Day
FROM
 [CustmrSrc]
WHERE
    DATENAME(dw,PurchaseDate) = 'Monday'
 OR DATENAME(dw,PurchaseDate) = 'Tuesday'
 OR DATENAME(dw,PurchaseDate) = 'Wednesday'
 OR DATENAME(dw,PurchaseDate) = 'Thursday'
 OR DATENAME(dw,PurchaseDate) = 'Friday'
GROUP BY
  CustName
 ,PurchaseDate



一些注释:

- 这里你需要OR条件,而不是AND。给定日期不能同时是星期一和星期二。

- 由于您已在GROUP BY子句中包含PurchaseDate列,因此您无需还包括日期名称(PurchaseDate)已经定义了工作日。



亲切。


A few notes:
- Here you need OR conditions, not AND. A given date cannot be a monday and a tuesday at the same time.
- Since you already included the PurchaseDate column in the GROUP BY clause, you do not need to also include the day name (the PurchaseDate already defines the week-day).

Kindly.


您传递要分组的表达式而不是别名

如下所示

You pass the expression you want to group by rather than the alias
Like below
select CustName,Count(CustName),PurchaseDate,DATENAME(dw,PurchaseDate) as Day from [CustmrSrc] A

where DATENAME(dw,PurchaseDate) = 'Monday' or DATENAME(dw,PurchaseDate) ='Tuesday' or  DATENAME(dw,PurchaseDate)='Wednesday' or DATENAME(dw,PurchaseDate)='Thursday'or DATENAME(dw,PurchaseDate)='Friday'

Group By CustName, PurchaseDate ,DATENAME(dw,PurchaseDate)


这篇关于在groupby子句中包含用户定义的列是不正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆