我有两个独立的表LPG_usage和设备。在LPG_usage表中有5列as (Device_id、Cylinder_Type、Date、Kg、Data_index ),设备表中有3列as (Device_id、User_name、Location)。
我希望通过考虑所有_id的LPG_usage表中的日期来选择最新的记录,并在设备表中使用Location。选定的表包括(Device_id,Cylinder_Type,Date,Kg,Location)
我对此进行了查询,但在'on子句‘中作为未知列'td.Device_id’获得了错误,我的代码如下所示
select t.Device_id, t.Date, t.Kg,t.Cylinder_Type,td.Location
from lpg_usage t
inner join (
select Device_id, max(Date) as Last_upDate
from lpg_usage
group by Device_id
) tm
INNER JOIN (
SELECT Location FROM devices
)td on t.Device_id = tm.Device_id and t.Date = tm.Last_upDate and t.Device_id = td.Device_id我真的很感谢你的帮助,谢谢
发布于 2021-06-03 19:38:37
错误消息是因为td子查询没有device_id。您可以通过将SELECT Location FROM devices更改为SELECT device_id, Location FROM devices来添加它。您还需要将连接的on中的一些条件移到td,以便将联接的新on移到tm。
select t.Device_id, t.Date, t.Kg,t.Cylinder_Type,td.Location
from lpg_usage t
inner join (
select Device_id, max(Date) as Last_upDate
from lpg_usage
group by Device_id
) tm
on t.Device_id = tm.Device_id and t.Date = tm.Last_upDate
INNER JOIN (
SELECT device_id, Location FROM devices
)td
on t.Device_id = td.Device_id上面的内容应该可以工作,但我不清楚为什么您有td的子查询。我建议考虑:
select t.Device_id, t.Date, t.Kg,t.Cylinder_Type,td.Location
from lpg_usage t
inner join (
select Device_id, max(Date) as Last_upDate
from lpg_usage
group by Device_id
) tm
on t.Device_id = tm.Device_id and t.Date = tm.Last_upDate
INNER JOIN devices td
on t.Device_id = td.Device_id另一种可供考虑的关于现代发展银行的办法是:
SELECT device_id, data, kg, cylinder_type, location
FROM
(
select t.Device_id, t.Date, t.Kg, t.Cylinder_Type, td.Location, RANK() OVER(PARTITION BY t.device_id ORDER BY t.data DESC) rk
from lpg_usage t INNER JOIN devices td
on t.Device_id = td.Device_id
)
WHERE rk = 1内部查询使用一个窗口函数(RANK)为每个device_id按给定的顺序(t.date DESC)对结果进行编号。外部查询仅用于获取每个device_id的最大日期。这使用RANK,因此它将返回多个领带行(如原始查询)。您可以使用ROW_NUMBER,如果您希望只得到一个记录时,有一个平分的日期。
https://stackoverflow.com/questions/67827078
复制相似问题