我正在尝试运行查询,并且在运行以下查询时工作正常:
SELECT 'Delivery' activity_type,
left(pod.ID1, charindex('*', pod.ID1) - 1) load_number,
DATEADD(hour, CONVERT(INT, LEFT(CONVERT(VARCHAR(2), ISNULL(Dock_In_Time,
'0')), 2)), CONVERT(DATETIME, ID2)) expected_arrival
FROM [Server].[Database].[dbo].[POD_Sched_Del] pod
--WHERE expected_arrival between '6/7/18' and '6/8/18'
ORDER BY expected_arrival asc, activity_type
当我添加注释中的以下代码行时:
--WHERE expected_arrival between '6/7/18' and '6/8/18'
我收到以下错误消息:
Msg 207, Level 16, State 3, Line 37 Invalid column name 'expected_arrival'.
Msg 207, Level 16, State 3, Line 37 Invalid column name 'expected_arrival'.
答案 0 :(得分:1)
您不能在where子句中使用您使用的别名,该列中不存在该列。
您可以将where子句更改为您尝试别名的列:
WHERE DATEADD(hour, CONVERT(INT, LEFT(CONVERT(VARCHAR(2), ISNULL(Dock_In_Time,
'0')), 2)), CONVERT(DATETIME, ID2)) between '6/7/18' and '6/8/18'
答案 1 :(得分:1)
将原始查询包装为派生表(子查询),然后您可以拥有该WHERE子句条件:
select *
from
(
SELECT 'Delivery' activity_type,
left(pod.ID1, charindex('*', pod.ID1) - 1) load_number,
DATEADD(hour, CONVERT(INT, LEFT(CONVERT(VARCHAR(2), ISNULL(Dock_In_Time,
'0')), 2)), CONVERT(DATETIME, ID2)) expected_arrival
FROM [Server].[Database].[dbo].[POD_Sched_Del] pod
) dt
WHERE expected_arrival between '6/7/18' and '6/8/18'
ORDER BY expected_arrival asc, activity_type