请帮我纠正查询。别名“startDate”无法识别。
SELECT TOP 1 a.[ID]
,b.[Name]
,a.[VName]
,a.[StartKM]
,a.[RecurringKM]
,dateadd (day,-(120000 - a.[StartKM])/80,GETDATE())as startDate
,dateadd(day,(a.[RecurringKM]/80),[startDate])as [DueDate]
FROM MaintenanceEventInstance AS a
INNER JOIN MaintenanceEventDescriptor AS b ON a.ID=b.ID
WHERE a.VName='test' AND a.CompletedDate IS NULL AND
a.ReType='4'
order by [DueDate] asc
任何帮助将不胜感激。
答案 0 :(得分:2)
您无法在SELECT
子句中使用别名。试试这个:
SELECT TOP 1 a.[ID]
,b.[Name]
,a.[VName]
,a.[StartKM]
,a.[RecurringKM]
,x.startDate
,dateadd(day,(a.[RecurringKM]/80),x.[startDate])as [DueDate]
FROM MaintenanceEventInstance AS a
INNER JOIN MaintenanceEventDescriptor AS b ON a.ID=b.ID
CROSS APPLY (SELECT dateadd (day,-(120000 - a.[StartKM])/80,GETDATE())) AS x(startDate)
WHERE a.VName='test' AND a.CompletedDate IS NULL AND
a.ReType='4' order by [DueDate] asc
答案 1 :(得分:1)
您不能在同一个选择中使用列别名,而是在那里添加表达式
SELECT TOP 1 a.[ID]
,b.[Name]
,a.[VName]
,a.[StartKM]
,a.[RecurringKM]
,dateadd (day,-(120000 - a.[StartKM])/80,GETDATE())as startDate
,dateadd(day,(a.[RecurringKM]/80),dateadd (day,-(120000 - a.[StartKM])/80,GETDATE()))as [DueDate]
FROM MaintenanceEventInstance AS a
INNER JOIN MaintenanceEventDescriptor AS b ON a.ID=b.ID
WHERE a.VName='test' AND a.CompletedDate IS NULL AND
a.ReType='4' order by [DueDate] as