[英]SQL Server 2005 sub query
我有一個wo_records
表,希望能夠以開始時間為每台機器提取當前的工作指令。
我編寫了此查詢來對每條記錄進行排名,並給最新條目的排名為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的行的正確方法是什么?
謝謝,
一致的回答看起來很棒。
我只想向您介紹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
除非我缺少任何東西,否則您要找的就是這個嗎?
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.