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

How can I use calculated alias in Order by clause?

table很简单:

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

datediff是在select子句之后计算的吗?任何人都可以解释吗?谢谢

您可以简单地使用 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);

似乎 management studio 的引擎无法将别名 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 我们使用要排序的列的编号。所以,你的代码没有任何问题。