2015年6月16日 星期二

【SQL】Using ORDER BY both in query and subquery

在主+子查詢中均使用排序

問題是我在主查詢跟子查詢中都使用 order by 如以下
SELECT TOP (1) WORKDAY FROM 
(
    SELECT TOP (2) CAST(WORKDAY AS DATE) AS 'WORKDAY' 
    FROM T_WORKDATE 
    WHERE (ISWORKING = 1) 
    ORDER BY WORKDAY DESC
) 
ORDER BY WORKDAY ASC
會出現 接近關鍵字 'ORDER' 之處的語法不正確。
結果好像 FROM 來源為主查詢時要 ORDER BY 一定要有別名
SELECT TOP (1) WORKDAY FROM 
(
    SELECT TOP (2) CAST(WORKDAY AS DATE) AS 'WORKDAY' 
    FROM T_WORKDATE 
    WHERE (ISWORKING = 1) 
    ORDER BY WORKDAY DESC
) tmpName 
ORDER BY WORKDAY ASC
加上 tmpName 就編過了

沒有留言:

張貼留言