这是我的表和查询
表1
AsOfDate Value
2015-06-06 11:08:21.247 5
2015-06-06 12:08:21.247 7
2015-06-07 10:08:21.247 8
2015-06-08 11:08:21.247 8
2015-06-08 10:09:21.247 9
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, [AsOfDate])) as DateOnly ,Min([Value])
FROM Table1 group by DateOnly
我收到错误消息“无效的列名'DateOnly'。”
实现它的最佳方法是什么?
答案 0 :(得分:3)
更改您的查询:
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, [AsOfDate])) as DateOnly ,Min([Value])
FROM Table1 group by DateOnly
要
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, [AsOfDate])) as DateOnly ,Min([Value])
FROM Table1 group by DATEADD(dd, 0, DATEDIFF(dd, 0, [AsOfDate]))
别名DateOnly
已知为查询级别(仅限于其顶部)
答案 1 :(得分:2)
你必须group by DATEADD(dd, 0, DATEDIFF(dd, 0, [AsOfDate]))
。很遗憾,您无法在group by
子句中使用别名。
答案 2 :(得分:2)
此处DateOnly
是列别名。因此,请在GROUP BY
中使用表达式本身
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, [AsOfDate])) as DateOnly ,Min([Value])
FROM Table1
group by DATEADD(dd, 0, DATEDIFF(dd, 0, [AsOfDate]))
答案 3 :(得分:2)
您没有使用从datetime
数据中删除时间部分的最佳方法。如果您使用支持date
数据类型的SQL Server版本,只需使用CAST(AsOfDate as date)
,或者您可以使用:CAST(CAST(AsOfDate as int) as datetime)
所以查询可以是这样的:
SELECT CAST(AsOfDate as date) as DateOnly ,Min([Value])
FROM Table1
GROUP BY CAST(AsOfDate as date)