1

我正在尝试在 SQL 语句中使用 CAST(),但它不允许我在 group by 中将 CAST(myDateTime, Date) 视为 myLoginShortDate?我只知道 SQL 的基础知识,我正在努力学习更多。
5 月数据如下所示:

CustomerID int, null Email 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'”

我希望能够看到:

电子邮件、登录日期、失败计数

xyz@test.com, 11/01/12, 21

abc@test2.com, 11/01/12, 17

xyz@test.com, 10/30/12, 15

等等。我确信这只是一个初学者的错误。我把这篇文章搞砸了,但我希望有人能理解。选择格式在我的电脑上看起来更好。

4

2 回答 2

2

GROUP BY语句在语句之前进行评估SELECT,因此 SQL Server 不知道您在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 指出的那样

于 2012-11-16T20:12:44.617 回答
0

SELECTstatement 在子句之后(逻辑上)执行GROUP BY,因此GROUP BY子句看不到该 alias 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
于 2012-11-16T20:14:36.427 回答