2

我在尝试为新列创建别名并在 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'.

如何解决问题?

4

2 回答 2

4

子查询怎么样?

在 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(...))似乎返回了简单的日期。你能解释一下我错过了什么吗?

于 2012-10-27T23:53:24.477 回答
1

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

于 2012-10-28T09:56:48.440 回答