sql achieve the same table id take time to maximum use of distinct on line

Such data tables are

select * from water_level_records  m where (
        select count(*) from water_level_records n where m.device_id = n.device_id and m.record_time < n.record_time
        ) < 1

This logic is sql the two tables as a table used to associate, <i.e. returns 1 only when that m is equal to a recording time is less than the number n of the recording time, i.e., it is the maximum time, if <2 is the value of the top two, here is uniquely associated with device_id

A method as more funny

SELECT DISTINCT on (device_id ) device_id  ,record_time from water_level_records order by device_id , record_time desc 

Here DISTINCT on the usage and effects DISTINCT different, if there is device_id as DISTINCT record_tiem these two columns have a different satisfied uniqueness. The effect is distinct on the matter followed a few columns, you must maintain the uniqueness of device_id 

Here plus order by the effect record_time desc just take time for the biggest one. Notice also that the DISTINCT on (device_id) if the rate of order by order by device_id if required

Reproduced in: https: //www.cnblogs.com/wangshaowei/p/11042392.html

Guess you like

Origin blog.csdn.net/weixin_34221276/article/details/93720537