与主字段不同的表中的值的聚合函数(Max)

时间:2014-01-21 05:30:26

标签: sql max inner-join aggregate-functions

我有两张桌子:

merchant:拥有商家可用的所有zipcodes(如果商家有10个地点,则会在此表中显示10次) 字段:merchant_id,Zipcode。 merchant_id是主键。

subdiv:拥有国家/地区的所有zipcodes和每个zip code字段中的订阅者数量:.subs,Zipcode邮政编码是主键。 Subs是邮政编码区域中的订户数量。

我希望获得所有商家的列表,其中邮政编码的子邮件数量最多。

这是我的解决方案:

select mr.merchant_id, m.zipcode 
from merchant mr 
join subdiv su on su.zipcode = mr.zipcode
join (select merchant_id, max(subs) as max_subs 
from merchant mr2 join subdiv su2 on su2.zipcode = mr2.zipcode group by 1
) as mr3 on mr3.merchant_id = mr.merchant_id and su.subs = mr3.max_subs

2 个答案:

答案 0 :(得分:0)

如果您一次只查询一个商家,则可以这样做:

select mr.merchant_id, mr.zipcode, su.subs
from merchant mr
    join subdiv su on su.zipcode = mr.zipcode
order by su.subs desc
where mr.merchant_id = ?
limit 1

对于多个merchant_id一次应该有效(我还没有测试过)的另一个查询是这样的:

select mr.merchant_id, mr.zipcode, su.subs
from merchant mr
    join subdiv su on su.zipcode = mr.zipcode
where su.subs =
    (select max(su2.subs) from subdiv su2 where su2.zipcode in 
        (select mr2.zipcode from merchant mr2 where mr2.merchant_id = mr.merchant_id)
    )
order by mr.merchant_id, mr.zipcode

请注意,如果多个zip_code的订阅者数量与该商家的max()相同,则会为商家返回多行。如果我没有出现任何语法错误,这应该比您提供的查询执行得更好。祝你好运!

答案 1 :(得分:0)

select max(subs) as Subs,mr.merchant_id, mr.zipcode 
  from merchant mr 
  left join subdiv su on su.zipcode = mr.zipcode
  group by mr.zipcode,mr.merchant_id