2015-10-16 238 views
0

我有一個wo_records表,希望能夠以開始時間提取每臺機器的當前工作訂單。SQL Server 2005子查詢

我寫此查詢排名每個記錄,並給出了最新的入門的秩爲1,但我無法巢它在那裏我可以使用where子句(where rank =1)

SELECT 
    *, 
    RANK() OVER (PARTITION BY get_address ORDER BY t_start desc) AS Last_value 
FROM 
    wo_records 

輸出:

ndx|Wo  | t_start     |t_end    | get_address| Rank 
-------------------------------------------------------------------------------- 
45 12521231 2019-01-07 15:41:24.000 NULL     44   1 
46 12521231 2018-01-08 15:42:24.000 2018-01-08 15:47:24.000 44   2 
39 12521231 2016-01-21 15:43:24.000 2016-01-21 15:49:24.000 44   3 

嵌套此語句以僅檢索rank = 1的行的正確方法是什麼?

謝謝,

回答

1

除非我失去了一些東西,所有你要找的是這樣嗎?

Select * 
From  
(
    Select *, 
      RANK() over (PARTITION BY get_address order by t_start desc) AS Last_value 
    From wo_records 
) As A 
Where A.Last_value = 1 
+0

是的,「AS A」究竟做了什麼? – Jad

+1

它將子查詢別名,以便它可以被引用。 – Siyual

+0

我正在嘗試使用INTO #temp做同樣的事情, – Jad

2

Siyual答案看起來不錯。

我只想告訴你關於CTE。這樣你就可以有幾個派生表,也有別名,易於閱讀。

WITH alias1 AS (
    Select *, 
      RANK() over (PARTITION BY get_address order by t_start desc) AS Last_value 
    From wo_records 
), 
anotherAlias AS (
    SELECT * .... 
) 
Select * 
From alias1 A -- optional can also include [anotherAlias] 
Where A.Last_value = 1