如何使用 sql 服务器中的组子句从每个组获取最新记录
How to get the latest record from each group using group clause in sql server
我想通过设备时间戳获取每个组订单的前 1 条记录,这样我就可以获得每个 device/imei 的前 1 条记录。
SQL
select
o.DeviceTimeStamp, o.DeviceImei, o.OTI_A,OTI_T,
ts.latitude, ts.longitude
from
Overview o
left join
TransformerLocations ts on o.DeviceImei = ts.imei
where
ts.latitude is not null
order by
o.DeviceTimeStamp desc
示例数据
2020-11-23 01:03:07.000 8673220311024 0 0 23.842163 91.280693
2020-11-23 01:01:06.000 8673220311024 0 0 23.842163 91.280693
2020-11-23 01:00:00.000 8645020301067 0 0 23.841940 91.280306
预期输出:
2020-11-23 01:03:07.000 8673220311024 0 0 23.842163 91.280693
2020-11-23 01:00:00.000 8645020301067 0 0 23.841940 91.280306
get top 1 record of each device/imei
一个选项使用 window 个函数:
select *
from (
select o.devicetimestamp, o.deviceimei, o.oti_a,oti_t,
ts.latitude, ts.longitude,
row_number() over(partition by o.deviceimei order by o.devicetimestamp desc) rn
from overview o
inner join transformerlocations ts on o.deviceimei = ts.imei
where ts.latitude is not null
) t
where rn = 1
请注意,我将 left join
更改为 inner join
:您在 where
子句中的“右”table 中有一个条件,因此连接行为作为 inner join
无论如何。
我想通过设备时间戳获取每个组订单的前 1 条记录,这样我就可以获得每个 device/imei 的前 1 条记录。
SQL
select
o.DeviceTimeStamp, o.DeviceImei, o.OTI_A,OTI_T,
ts.latitude, ts.longitude
from
Overview o
left join
TransformerLocations ts on o.DeviceImei = ts.imei
where
ts.latitude is not null
order by
o.DeviceTimeStamp desc
示例数据
2020-11-23 01:03:07.000 8673220311024 0 0 23.842163 91.280693
2020-11-23 01:01:06.000 8673220311024 0 0 23.842163 91.280693
2020-11-23 01:00:00.000 8645020301067 0 0 23.841940 91.280306
预期输出:
2020-11-23 01:03:07.000 8673220311024 0 0 23.842163 91.280693
2020-11-23 01:00:00.000 8645020301067 0 0 23.841940 91.280306
get top 1 record of each device/imei
一个选项使用 window 个函数:
select *
from (
select o.devicetimestamp, o.deviceimei, o.oti_a,oti_t,
ts.latitude, ts.longitude,
row_number() over(partition by o.deviceimei order by o.devicetimestamp desc) rn
from overview o
inner join transformerlocations ts on o.deviceimei = ts.imei
where ts.latitude is not null
) t
where rn = 1
请注意,我将 left join
更改为 inner join
:您在 where
子句中的“右”table 中有一个条件,因此连接行为作为 inner join
无论如何。