Sql 查找每个组的最大记录,以及其他字段
我有一个名为Sql 查找每个组的最大记录,以及其他字段,sql,max,inner-join,Sql,Max,Inner Join,我有一个名为tgps的表,它有六个字段和数据 Model ftype serial Date latitude longitude Car B 2142 15/09/2014 S11.59.41.194 W077.07.33.184 Car A 2123 15/09/2014 S12.15.12.245 W076.55.08.194 Truck A 2123 16/09/2
tgps
的表,它有六个字段和数据
Model ftype serial Date latitude longitude
Car B 2142 15/09/2014 S11.59.41.194 W077.07.33.184
Car A 2123 15/09/2014 S12.15.12.245 W076.55.08.194
Truck A 2123 16/09/2014 S13.42.48.122 W071.53.22.081
PickUp C 2111 14/09/2014 S14.36.05.071 W075.11.47.133
PickUp A 2111 15/09/2014 S14.39.51.245 W075.10.00.000
PickUp A 2111 14/09/2014 S14.41.14.040 W075.07.12.245
Truck B 2123 13/09/2014 S14.42.51.092 W075.05.35.133
Car B 2142 14/09/2014 S14.46.14.040 W070.20.03.030
Truck A 2123 13/09/2014 S15.54.53.163 W071.11.21.153
Truck B 2123 16/09/2014 S15.58.40.051 W071.12.48.122
Car A 2123 16/09/2014 S16.18.06.061 W069.16.24.122
Car C 2142 13/09/2014 S16.29.27.092 W071.51.48.122
这需要一个带有连接字段的内部联接(Model
、ftype
和serial
),我尝试了以下方法:
SELECT model + ftype + serial, date, latitude, longitude
FROM (
SELECT model + ftype + serial, max(date)
FROM tgps group by model, ftype, serial)
as xw inner join tgps on tgps.model + tgps.ftype + tgps.serial = xw.model + xw.ftype + xw.serial
and tgps.date = xw.max(date)
但它不起作用。您可以使用CTE获取每个型号、ftype和序列的最长日期。然后,您可以将其连接到表中,以获得这些值的lat和long。
您可以选择日期更大且型号、ftype和serial相同的另一行不存在的所有行
select * from tgps t1
where not exists (
select 1 from tgps t2
where t2.model = t1.model
and t2.ftype = t1.ftype
and t2.serial = t1.serial
and t2.date > t1.date
)
或者,如果您可以访问分析函数,这将更快
select * from (
select *,
row_number() over (partition by model, ftype, serial order by date desc) rn
from tgps) t1 where rn = 1
您可以使用链接到主选择的简单子查询来获取每个实体的最大日期:
select
Model, ftype, serial, Date, latitude, longitude
from
tgps T
where
Date =
(
select
max(Date)
from
tgps
where
Model = T.Model
and ftype = T.ftype
and serial = T.serial
)
谢谢大家,这就是我解决问题的方法:
SELECT tgps.model + tgps.ftype + tgps.serial,tgps.lat, tgps.lng, tgps.Date FROM tgps INNER JOIN (
SELECT model, ftype, serial, max(Date) junto
FROM tgps group by model, ftype, serial)
as xw on tgps.Date = xw.junto and tgps.serial = xw.serial and tgps.ftype = xw.ftype and tgps.model = xw.model
尝试使用concat | |代替+SQL的最后一部分对我来说没有多大意义。它可能应该是
tgps.date=Max(xw.date)
我不会对此做更多的研究,所以谁知道这是否有效。如果您将SQL格式化为可读性更好,它可能会得到更多答案。此外,“不工作”可能是对stackoverflow问题最糟糕的描述。将来提供日志和错误消息。的可能重复项
select
Model, ftype, serial, Date, latitude, longitude
from
tgps T
where
Date =
(
select
max(Date)
from
tgps
where
Model = T.Model
and ftype = T.ftype
and serial = T.serial
)
SELECT tgps.model + tgps.ftype + tgps.serial,tgps.lat, tgps.lng, tgps.Date FROM tgps INNER JOIN (
SELECT model, ftype, serial, max(Date) junto
FROM tgps group by model, ftype, serial)
as xw on tgps.Date = xw.junto and tgps.serial = xw.serial and tgps.ftype = xw.ftype and tgps.model = xw.model