我将在本文末尾发布我的查询,但首先需要说明。请忽略列名和表名,但我在两个地方有语法错误。当我将此查询与我的 CTE 一起使用时,它告诉我必须首先“用 ; 终止前一个语句” 然后我在 CTE 中使用别名列名,然后它说“无法绑定多部分标识符“E.ActiveAGVs”。
我希望我能很好地解释我的问题。如果有人能看到我正在尝试做的事情并让我知道它是否会起作用或纠正我的语法错误,我将非常感激。
Select A.move_hour as 'Hour',
isnull(B.move_count,0) as 'Current_Count',
isnull(C.move_count,0) as '1_Day_Previous',
isnull(D.move_count,0) as '2_Day_Previous',
ISNULL (E.ActiveAGVs,0) as 'Active AGV''s'
--^ Error right here
from
(select distinct(DATEPART(HH, Move_History.Move_Dt)) as move_hour
from Move_History
where Plant_Id = 1 and Building_Id = 1) as A
left outer join
(select datepart(HH,Move_History.Move_Dt) as move_hour,
Move_History.Move_Cnt as move_count
from Move_History
Group by datepart(HH,Move_History.Move_Dt), Move_Cnt) as B on A.move_hour = B.move_hour
left outer join
(select datepart(HH,Move_History.Move_Dt) as move_hour, Move_History.Move_Cnt as move_count
from Move_History
Group by datepart(HH,Move_History.Move_Dt), Move_Cnt) as C on A.move_hour = C.move_hour
left outer join
(select datepart(HH,Move_History.Move_Dt) as move_hour, Move_History.Move_Cnt as move_count
from Move_History
Group by datepart(HH,Move_History.Move_Dt), Move_Cnt) as D on A.move_hour = D.move_hour;
with const as (
select cast(cast(getdate() as date) as datetime) as midnight
),
allhours as (
select 0 as m_hour, midnight as timestart, dateadd(hour, 1, midnight) as timeend from const union all
...
select 23 as m_hour, dateadd(hour, 23, midnight) as timestart, dateadd(hour, 24, midnight) as timeend from const
)
(select ah.m_hour,
(sum(datediff(SECOND, timestart), ah.timeend else dt.End_Dt end))
/ 18000.0) * 5 as ActiveAGVs
from allhours as ah
left outer join AGV_Report as dt
on ah.timestart< coalesce(dt.End_dt, getdate()) and
ah.timeend >= dt.Begin_Dt
Group by datepart(SECOND,ah.hour), ah.timestart) as E on A.move_hour = E.move_hour
--^ 'Incorrect syntax near "as"'
where A.move_hour is not null
order by ah.m_hour asc