我试图在SQL语句中使用CAST(),但它不允许我在组中看到CAST(myDateTime,Date)为myLoginShortDate?我只知道SQL的基础知识,我想了解更多。
可能数据如下:
CustomerID int,null 电子邮件varchar(60) DateEntered DateTime
我正在尝试按日期时间的日期部分进行分组,并将其分组到电子邮件
我的存储过程选择部分如下所示:
select cll.Email,CAST(cll.DateEntered as Date) as LoginDate,
COUNT(cll.email) as FailedCount
from [GC].[dbo].[CustomerLoginLog] as cll
where [CustomerId] is null
group by LoginDate, cll.Email
order by FailedCount desc`
它返回“无效的列名'LoginDate'”
我希望能够看到:
电子邮件,LoginDate,FailedCount
xyz@test.com,11 / 01 / 12,21
abc@test2.com,11 / 01 / 12,17
xyz@test.com,10 / 30 / 12,15
等等。我确信这只是初学者的错误。我有这个帖子搞砸了但我希望有人理解它。我的电脑上的选择格式看起来更好。
答案 0 :(得分:2)
在GROUP BY
语句之前评估SELECT
语句,因此SQL服务器不知道您在SELECT
语句中给出表达式的别名。要解决此问题,您只需在GROUP BY
:
GROUP BY CAST(cll.DateEntered AS Date)
或者用CTE包装查询的简单部分,并对CTE结果进行分组:
;WITH MyQuery AS
(
SELECT
cll.Email
,CAST(cll.DateEntered AS Date) AS LoginDate
FROM
[GC].[dbo].[CustomerLoginLog] AS cll
WHERE
cll.[CustomerId] IS NULL
)
SELECT
Email
,LoginDate
,COUNT(*) AS FailedCount
FROM
MyQuery
GROUP BY
LoginDate, Email
ORDER BY
FailedCount DESC
或者,您可以将嵌套的SELECT语句中的CTE内容包含在Mahmoud pointed out中。
答案 1 :(得分:0)
SELECT
语句(逻辑上)在GROUP BY
子句之后执行,因此GROUP BY
子句无法看到该别名LoginDate
。你必须使用一种子查询,或像这样的CTE:
SELECT *
FROM
(
SELECT
cll.Email,
CAST(cll.DateEntered as Date) as LoginDate,
COUNT(cll.email) as FailedCount
FROM [GC].[dbo].[CustomerLoginLog] as cll
WHERE [CustomerId] IS NULL
) t
GROUP BY LoginDate, cll.Email
ORDER BY FailedCount DESC