昨天我问了一个复杂查询的问题,我得到了一个例子。我真的想让它工作,但它有一个语法错误,我无法弄清楚。请记住,本周早些时候我刚刚介绍过CTE,所以希望这很简单。
我认为我不需要在这里发布完整的代码,所以我只是总结一下
with cte as (select dateadd(hour, 1, cast(cast(getdate() -1 as date) as datetime)) as midnnight),
allhours as (
select 0 as hour, midnight as timestart, dateadd(hour, 1, timestart) as timeend from cte union all
select 1 as hour, dateadd(hour, 1, midnight), dateadd(hour, 2, midnight) from cte union all
....
select 23 as hour, dateadd(hour, 23, midnight), dateadd(hour, 24, midnight) from cte union all
)
select ah.hour,...
(...)表示我省略的不必要的代码,使其不那么混乱
但是我在select 23和select ah.hour之间的括号上出现语法错误 “语法不正确')'。期待SELECT,或'('。
非常感谢任何帮助。
-J
答案 0 :(得分:1)
您有一些语法错误,包括底部不需要的UNION ALL
,而SELECT
中的第一个allhours
引用了别名,请尝试以下操作:
;with cte as
(
select dateadd(hour, 1, cast(cast(getdate() -1 as date) as datetime)) as midnight
),
allhours as
(
select 0 as hour, midnight as timestart, dateadd(hour, 1, midnight) as timeend
from cte
union all
select 1 as hour, dateadd(hour, 1, midnight), dateadd(hour, 2, midnight)
from cte
union all
select 23 as hour, dateadd(hour, 23, midnight), dateadd(hour, 24, midnight)
from cte
)
select *
from allhours
答案 1 :(得分:0)
你应该摆脱最后的Union all
hour, dateadd(hour, 23, midnight), dateadd(hour, 24, midnight) from cte union all
)
select ah.hour,...
另外,拼写在第一行的午夜