SQL Server 2005 子查询

SQL Server 2005 sub query

我有一个wo_recordstable,希望能够提取每台机器的当前工单和开始时间。

我写了这个查询来对每条记录进行排名,并将最新条目的排名设为 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

嵌套此语句以仅检索排名为 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

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