如何在Order by子句中使用计算出的别名?

时间:2019-09-13 02:19:16

标签: sql-server tsql sql-order-by datediff

表很简单:

ID   start_date    end_date
1    2015-10-01    2015-10-02
2    2015-10-02    2015-10-03
3    2015-10-05    2015-10-06
4    2015-10-07    2015-10-08

ID 1和2属于一个项目,因为end_date等于start_date,ID 3和4是不同的项目。

以下是用于查询相同项目并按时间进行排序的查询:

select P1.Start_Date, (
    select min(P.End_Date)
    from Projects  as P
    where P.End_Date not in (select Start_Date from Projects )
        and P.End_Date > P1.Start_Date
) as ED
from Projects as P1
where P1.Start_Date not in (select End_Date from Projects )
order by datediff(day, P1.Start_Date, ED)

问题是:ED在order by子句中无效,但在不使用datediff的情况下有效:

order by ED

在select子句之后计算datediff吗?有人可以解释吗?谢谢。

1 个答案:

答案 0 :(得分:0)

您可以简单地使用CROSS APPLY来计算此列,如下所示:

DECLARE @Projects TABLE
(
    [ID] SMALLINT
   ,[start_date] DATETIME
   ,[end_date] DATETIME
);

INSERT INTO @Projects ([ID], [start_date], [end_date])
VALUES ('1', '2015-10-01', '2015-10-02')
      ,('2', '2015-10-02', '2015-10-03')
      ,('3', '2015-10-05', '2015-10-06')
      ,('4', '2015-10-07', '2015-10-08');

select P1.Start_Date, ED
from @Projects as P1
CROSS APPLY
(
    select min(P.End_Date)
    from @Projects  as P
    where P.End_Date not in (select Start_Date from @Projects )
        and P.End_Date > P1.Start_Date
) DS(ED)
where P1.Start_Date not in (select End_Date from @Projects )
order by datediff(day, P1.Start_Date, ED);

管理工作室的引擎似乎无法将别名ED转换为有效的名称。例如,如果用子查询替换ED,它将起作用。另外,下面的一种不好的做法也会起作用:

select P1.Start_Date, (
    select min(P.End_Date)
    from @Projects  as P
    where P.End_Date not in (select Start_Date from @Projects )
        and P.End_Date > P1.Start_Date
) as ED
from @Projects as P1
where P1.Start_Date not in (select End_Date from @Projects )
order by datediff(day, P1.Start_Date, 2)

相反,我们使用alias来排序的列号。因此,您的代码没有错。