简体   繁体   English

相当于为mysql保留dense_rank

[英]Equivalent of keep dense_rank for mysql

I have this table 我有这张桌子

create table  sd_devices (
device_code varchar(128),
vin varchar(128),
created_at  datetime,
loaded_at   datetime
)

I would like to select for each device_code the first vin order by created_at desc, loaded_at desc . 我想通过created_at desc, loaded_at desc为每个device_code选择第一个vin顺序。

In oracle, I would have use keep dense_rank , but here with MySQL i do not know how to do that. 在oracle中,我会使用keep dense_rank ,但在这里使用MySQL我不知道该怎么做。

this should do it: 这应该这样做:

SELECT DISTINCT device_code,
       vin
       FROM (
SELECT sd_devices.*
FROM sd_devices
ORDER BY created_at DESC, loaded_at DESC ) AS a
GROUP BY device_code

In the subquery you select all the rows and order them in the correct order, Then in the outside query you use DISTINCT to get rid of any Duplicate rows and it will use the first one it encounters. 在子查询中,您选择所有行并按正确的顺序对它们进行排序,然后在外部查询中使用DISTINCT来删除任何重复行,它将使用它遇到的第一行。 Because we already put it in the correct order it will grab the one row we want. 因为我们已经按照正确的顺序放置它,它将抓住我们想要的一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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