SQL别名为Group By提供“无效列名”

时间:2012-10-27 22:20:59

标签: tsql

我在尝试为新列创建别名并在GROUP BY子句中使用它时遇到问题:

SELECT TOP 100 Percent
count(id) AS [items_by_day],    
(SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, [date]))) AS [date_part]
FROM [MyDB].[dbo].[MyTable]
GROUP BY DAY([date]), MONTH([date]), YEAR([date]), date_part

我收到以下错误:

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

如何解决问题?

2 个答案:

答案 0 :(得分:4)

子查询怎么样?

查看我的demo at sqlfiddle

Select  Count(*) as nrOfRecords, sq.[items_by_day], sq.[date_part] 
From (
    SELECT TOP 100 Percent count(id) AS [items_by_day]
      ,(Select Dateadd(dd, 0, Datediff(dd, 0, [date]))) AS [date_part]
    From  [MyTable] 
    Group By id, date
) as sq
Group by sq.[items_by_day], sq.[date_part]

部分(SELECT DateAdd(... DateDiff(...))似乎返回了明确的日期。你能解释我错过的东西吗?

答案 1 :(得分:1)

您不能在GROUP BY中使用列别名,别名用于显示,除非别名在子查询中,在这种情况下,它将成为列名。