SQL别名无法识别

时间:2016-07-04 06:09:11

标签: sql sql-server alias

请帮我纠正查询。别名“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

任何帮助将不胜感激。

2 个答案:

答案 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