gpt4 book ai didi

tsql - SQL 别名为 Group By 提供 "invalide column name"

转载 作者:行者123 更新时间:2023-12-02 05:25:43 24 4
gpt4 key购买 nike

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

如何解决这个问题?

最佳答案

子查询怎么样?

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

关于tsql - SQL 别名为 Group By 提供 "invalide column name",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13104679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com