[英]SQL for each loop - how to
I have this example table: 我有这个示例表:
Machine_ID | ID | STATE
3210 | 543210 | ACTIVATION
3210 | 543789 | ACTIVE
1212 | 111111 | ACTIVE
1212 | 111222 | ACTIVE
4444 | 444444 | STOPPED
4444 | 555555 | STARTED
All i want to do is to get latest state of every machine (greater ID = later action) 我想做的就是获得每台机器的最新状态(更大的ID =以后的动作)
Pseudocode: 伪代码:
foreach Machine_ID
select * where ID greatest
My output table should look like: 我的输出表应如下所示:
Machine_ID | ID | STATE
3210 | 543789 | ACTIVE
1212 | 111222 | ACTIVE
4444 | 555555 | STARTED
Thanks for help in advice. 感谢您的建议帮助。 Please describe your solution, as many others can use it as well (i did not found following example in google or any tutorial).
请描述您的解决方案,因为许多其他人也可以使用它(我没有在谷歌或任何教程中找到以下示例)。 I use Oracle DB
我使用Oracle DB
You can get this using a keep
construct: 你可以使用
keep
构造来获得:
select machine_id, max(id),
max(state) keep (dense_rank first order by id desc) as laststate
from machines m
group by machine_id;
Wherever possible, you should always take a set based approach to processing data. 只要有可能,您应始终采用基于集合的方法来处理数据。 In this case, you can do this by creating a derived table of the Max ID of each Machine (
GROUP
ed) and then JOIN
back to this derived table: 在这种情况下,您可以通过创建每台计算机的最大ID(
GROUP
ed)的派生表,然后JOIN
回到此派生表来执行此操作:
SELECT m.MachineID, m.ID, m.State
FROM Machine m
INNER JOIN
(
SELECT MachineID, MAX(ID) AS MaxID
FROM Machine
GROUP BY MachineID) x
ON m.MachineID = x.MachineID
AND m.ID = x.MaxID;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.