ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效


77

除非还指定了TOP,OFFSET或FOR XML,否则ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效。

我在尝试执行以下查询时遇到上述错误。谁能看看我在这里做错了什么吗?

SELECT 
    * 
FROM (
    SELECT 
        Stockmain.VRNOA, 
        item.description as item_description, 
        party.name as party_name, 
        stockmain.vrdate, 
        stockdetail.qty, 
        stockdetail.rate, 
        stockdetail.amount, 
        ROW_NUMBER() OVER (ORDER BY VRDATE) AS RowNum
    FROM StockMain 
    INNER JOIN StockDetail 
        ON StockMain.stid = StockDetail.stid 
    INNER JOIN party 
        ON party.party_id = stockmain.party_id 
    INNER JOIN item 
        ON item.item_id = stockdetail.item_id 
    WHERE stockmain.etype='purchase' 
    ORDER BY VRDATE DESC
) AS MyDerivedTable
WHERE 
    MyDerivedTable.RowNum BETWEEN 1 and 5   

2
的顺序应该在子查询选择之外(如错误所述)
Daniele

Answers:


87

您无需ORDER BY在内部查询afterWHERE子句中使用,因为您已经在中使用过它ROW_NUMBER() OVER (ORDER BY VRDATE DESC)

SELECT 
    * 
FROM (
    SELECT 
        Stockmain.VRNOA, 
        item.description as item_description, 
        party.name as party_name, 
        stockmain.vrdate, 
        stockdetail.qty, 
        stockdetail.rate, 
        stockdetail.amount, 
        ROW_NUMBER() OVER (ORDER BY VRDATE DESC) AS RowNum  --< ORDER BY
    FROM StockMain 
    INNER JOIN StockDetail 
        ON StockMain.stid = StockDetail.stid 
    INNER JOIN party 
        ON party.party_id = stockmain.party_id 
    INNER JOIN item 
        ON item.item_id = stockdetail.item_id 
    WHERE stockmain.etype='purchase' 
) AS MyDerivedTable
WHERE 
    MyDerivedTable.RowNum BETWEEN 1 and 5 

25
不,由于错误消息中给出的原因,您不能使用ORDER BY对派生表中的行进行排序。结果集中的行顺序最终由外部SELECT中的ORDER BY子句控制,而不是由OVER子句控制。的OVER子句“指定的逻辑,其中所述窗口functioncalculation执行顺序”。它不会对结果集进行排序。
Mike Sherrill'Cat Recall'13

13
ORDER BY column OFFSET 0 ROWS

令人惊讶的是它使它起作用,这真是一个奇怪的功能。

一个更大的示例,其中包含CTE作为临时“存储”长查询以在以后重新排序的一种方式:

;WITH cte AS (
    SELECT .....long select statement here....
)

SELECT * FROM 
(
    SELECT * FROM 
    ( -- necessary to nest selects for union to work with where & order clauses
        SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS 
    ) first
    UNION ALL
    SELECT * FROM 
    (  
        SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS 
    ) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example

所以我们得到所有结果的排序 MainCol

但是结果MainCol = 1ColX

结果与MainCol = 0排序ColY


4
任何人都可以瞥见Microsoft为什么需要这种荒唐的冗余附加语法吗?
黑色
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.