***
和***
中的查詢將生成按status_date
排序的分區行。現在,如果結果有多於一行的status_date
,那麼我只想按change_date
排序那些行。對sql服務器中的排序數據進行排序
我想出了下面的查詢,但它沒有給出想要的結果。
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
我得到以下錯誤:「ORDER BY子句在視圖,內聯函數,派生表,子查詢無效,和通用表表達式,除非指定了TOP,OFFSET或FOR XML。「 – BumbleBee 2013-05-08 21:21:12
查詢,內聯函數,派生表,子查詢或公用表表達式是查詢的一部分嗎?或者,你是否試圖在當前查詢中嵌入更改? – bobs 2013-05-08 21:24:46
我必須在LUV提到的查詢結尾處放置Order。 – BumbleBee 2013-05-08 21:31:22