1

***内部的查询***将生成按 排序的分区行status_date。现在,如果该结果有不止一行相同, status_date那么我只想对这些行进行排序change_date

我提出了以下查询,但没有给出预期的结果。

 SELECT  MID,status_date,status,change_date, row_number() OVER (PARTITION BY MID ORDER BY  change_date DESC )  as RN1, 1 as TimeRange
                    FROM 
                        (
                    *** SELECT MID,status_date,status,change_date,
                        rn = row_number() OVER (PARTITION BY MID ORDER BY status_date DESC)
                        FROM listing_History   (nolock)
                         WHERE  MID like  '12-572561'  ****

                        )  AS A

以供参考 :

内部查询的结果******

12-572561   2012-06-11 00:00:00.000 Canceled    2012-06-11 14:53:22.957  1
12-572561   2012-03-01 00:00:00.000 Canceled    2012-03-01 13:32:40.030  2
12-572561   2012-01-02 00:00:00.000 Active      2012-01-02 07:32:34.067  3
12-572561   2012-01-02 00:00:00.000 Active      2012-06-11 07:43:29.400  4
12-572561   2012-01-02 00:00:00.000 Active      2012-01-10 00:01:03.407  5
12-572561   2012-01-02 00:00:00.000 Active      2012-06-11 07:43:29.417  6

现有查询的结果:

12-572561   2012-06-11 00:00:00.000 Canceled    2012-06-11 14:53:22.957  1  1
12-572561   2012-01-02 00:00:00.000 Active      2012-06-11 07:43:29.417  2  1
12-572561   2012-01-02 00:00:00.000 Active      2012-06-11 07:43:29.400  3  1
12-572561   2012-03-01 00:00:00.000 Canceled    2012-03-01 13:32:40.030  4  1
12-572561   2012-01-02 00:00:00.000 Active      2012-01-10 00:01:03.407  5  1
12-572561   2012-01-02 00:00:00.000 Active      2012-01-02 07:32:34.067  6  1

期望的结果:

12-572561   2012-06-11 00:00:00.000 Canceled    2012-06-11 14:53:22.957  1  1
12-572561   2012-03-01 00:00:00.000 Canceled    2012-03-01 13:32:40.030  2  1
12-572561   2012-01-02 00:00:00.000 Active      2012-06-11 07:43:29.417  6  1
12-572561   2012-01-02 00:00:00.000 Active      2012-06-11 07:43:29.400  4  1
12-572561   2012-01-02 00:00:00.000 Active      2012-01-10 00:01:03.407  5  1
12-572561   2012-01-02 00:00:00.000 Active      2012-01-02 07:32:34.067  3  1
4

2 回答 2

2

您可以在查询结束时使用ORDER BY forchange_date

于 2013-05-08T20:08:56.863 回答
2

row_number() 函数不能确定结果的顺序。您需要一个 ORDER BY 子句。如果您不需要结果中的 row_number() 值,您可以执行以下操作

SELECT MID,status_date,status,change_date
FROM listing_History   (nolock)
WHERE  MID like  '12-572561'
ORDER BY status_date DESC, change_date DESC
于 2013-05-08T20:16:27.193 回答