SQL - ROW_NUMBER()OVER(ORDER BY)不起作用

时间:2012-03-30 04:11:47

标签: sql sql-server sql-server-2008 sql-order-by analytic-functions

我在ORDER BY子句中放置的内容并不重要,结果集的顺序不会改变。

WITH Results AS (
    SELECT DISTINCT 
        MessageThreadUsers.threadFK, 
        MessageThreads.threadDate, 
        Messages.MessageBody, 
        Messages.senderFK,
        Users.userFullName AS senderFullName, 
        ROW_NUMBER() OVER (ORDER BY MessageThreads.threadDate DESC) AS RowNumber

    FROM MessageThreadUsers
        JOIN MessageThreads ON MessageThreadUsers.threadFK = MessageThreads.threadID
        JOIN Messages ON MessageThreads.threadDate = Messages.messageDate
        JOIN Users ON Messages.senderFK = Users.userID

    WHERE userFK = 'usr_developer'
) 
SELECT * FROM Results WHERE RowNumber BETWEEN 1 AND 10

1 个答案:

答案 0 :(得分:7)

ORDER BY仅在将应用于最外层SELECT语句时控制返回行的顺序。

这可能会更好:

WITH Results AS (
    SELECT DISTINCT 
        MessageThreadUsers.threadFK, 
        MessageThreads.threadDate, 
        Messages.MessageBody, 
        Messages.senderFK,
        Users.userFullName AS senderFullName, 
        ROW_NUMBER() OVER (ORDER BY MessageThreads.threadDate DESC) AS RowNumber

    FROM MessageThreadUsers
        JOIN MessageThreads ON MessageThreadUsers.threadFK = MessageThreads.threadID
        JOIN Messages ON MessageThreads.threadDate = Messages.messageDate
        JOIN Users ON Messages.senderFK = Users.userID

    WHERE userFK = 'usr_developer'
) 
SELECT * FROM Results WHERE RowNumber BETWEEN 1 AND 10
ORDER BY RowNumber