[英]SQL Server 2005 sub query
I have a wo_records
table, want to be able to extract the current work order for each machine with the start time. 我有一个
wo_records
表,希望能够以开始时间为每台机器提取当前的工作指令。
I wrote this query to rank each records and gives the latest entry a rank of 1, but I'm unable to nest it where I can use a where clause (where rank =1)
我编写了此查询来对每条记录进行排名,并给最新条目的排名为1,但是我无法将其嵌套在可以使用where子句的位置
(where rank =1)
SELECT
*,
RANK() OVER (PARTITION BY get_address ORDER BY t_start desc) AS Last_value
FROM
wo_records
Output: 输出:
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
What is the correct way to nest this statement to retrieve only the rows with rank= 1? 嵌套此语句以仅检索rank = 1的行的正确方法是什么?
Thanks, 谢谢,
Siyual answer looks great. 一致的回答看起来很棒。
I just want show you about CTE . 我只想向您介绍CTE 。 This way you can have several derivated tables also with alias and easy to read.
这样,您可以拥有几个带有别名的派生表,并且易于阅读。
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
Unless I'm missing something, all you're looking for is this? 除非我缺少任何东西,否则您要找的就是这个吗?
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.