我有一个MS SQL DB表,我存储了部分状态日志,即。硬件部分如何在某处发生变化。
我需要为每个部分准确地获得一行(按日期排序),然后计算所有行,其中new_status
等于2.
现在举个例子,我提出了这个问题:
Select part_sys_id, old_status, new_status, sys_created
From Vhw_status_journal
Where i = 5
Order by sys_created desc
哪个让我(注意i
只是一个内部列):
part_sys_id | old_status | new_status | sys_created
-----------------------------------------------------------
21 | 2 | 3 | 2015-08-19 11:00:25
21 | NULL | 2 | 2015-08-19 10:59:28
20 | 1 | 2 | 2015-08-18 14:13:04
20 | 2 | 1 | 2015-08-17 10:51:03
20 | NULL | 2 | 2015-08-12 15:05:46
现在事实证明,当我必须获得每个part_sys_id的最新条目时,我完全迷失了(我试过Select Disctint
无效)然后甚至计算输出行new_status = 2。
我要求的输出是:
part_sys_id | old_status | new_status | sys_created
-----------------------------------------------------------
21 | 2 | 3 | 2015-08-19 11:00:25
20 | 1 | 2 | 2015-08-18 14:13:04
然后我需要用new_status = 2计算行数,即。我应该得到类似的东西:
count
-----
1
答案 0 :(得分:2)
试试这个
with cte
as
(
select row_number() over(partition by part_sys_id order by sys_created desc) as ri,part_sys_id, old_status, new_status, sys_created
from Vhw_status_journal
where i = 5
)
select count(*) from cte where ri=1 and new_status=2
答案 1 :(得分:0)
Select part_sys_id, old_status, new_status, max(sys_created )
From Vhw_status_journal Where i = 5 GROUP BY part_sys_id
这应该只给你每个part_sys_id中的一个,最新的。
编辑:小组必须在订单的前面。
EDIT2:使用order desc, limit 1
更好地使用max()
答案 2 :(得分:0)
我的同事给了mi这个查询,它也有效:
select count(*) from Vhw_status_journal
where sys_id =
(select max(sys_id)
from Vhw_status_journal Vhw_status_journal_alias
where Vhw_status_journal.part_sys_id = Vhw_status_journal_alias.part_sys_id)
and new_status = 2