首页 > 解决方案 > 在sql中使用group by连接两个表

问题描述

您好,我正在尝试加入这两个表,但无法加入。我单独拥有数据,但不幸的是我无法加入它们,因为表 nr 2 中涉及 group by 语句,这使得加入有点复杂。

表 1;-- 包括所有数据

SELECT i.attr,iv.dateofvalue,iv.price 
FROM information i, informationvalues iv
WHERE i.attr=iv.attr;

表 nr2;-- 仅包括不包括价格的最新数据

SELECT i.attr, MAX (iv.dateofvalue) AS recentdate
FROM information i, informationvalues iv
 WHERE i.attr=iv.attr 
 GROUP BY i.attr;

目标是通过从 table nr 1 获取 tablenr 2 以相应的价格扩展它。注意:recentdate=dateofvalue 希望有人能提供帮助,在此先感谢!

标签: mysqlsqlgroup-bygreatest-n-per-group

解决方案


您似乎正在寻找每个属性的最新价格。如果是这样,您可以使用相关子查询进行过滤,该子查询为您提供每个属性的最后日期:

select 
    i.attr,
    v.dateofvalue,
    v.price
from information i
inner join informationvalues v on v.attr = i.attr
where v.dateofvalue = (
    select max(v1.dateofvalue) from informationvalues v1 where v1.attr = v.attr
)

推荐阅读