简体   繁体   中英

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)

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

You can get this using a keep construct:

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:

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;

Sql fiddle Here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM