【问题标题】:SQL query to find the most number of vendors per a given location用于查找每个给定位置的最多供应商数量的 SQL 查询
【发布时间】:2020-12-21 19:55:27
【问题描述】:

您能帮我找到正确的 MySQL 查询,以获取每个给定位置的最多供应商数量,并按名称和商店名称列出所有供应商吗:

1 - 查询必须找出哪个位置的供应商数量最多,然后按名称和他们工作的商店的名称列出它们。

我有以下表格:

CITIES 
(
 ID "unique",
 NAME
)


SHOPS
(
 ID "unique",
 NAME,
 CITY_ID ( foreign key of CITIES TABLE ID)
)

VENDORS
(
 ID "unique",
 NAME,
 SHOP_ID ( foreign key of SHOPS TABLE ID)
)

虚拟数据示例

CITIES : NY, SF

SHOPS: Boom - NY, Flash - NY, Sofast - SF

Vendors:

Mark : Boom,
John : Boom,
Carlos : Sofast,
Alex : Sofast,
David : Flash,
James: Flash

纽约的供应商数量最多,因此应该列出

Mark : Boom, John : Boom, David : Flash, James: Flash

【问题讨论】:

标签: mysql sql count greatest-n-per-group window-functions


【解决方案1】:

检查这是否有效 -

Select vendors.name, shops.name 
from 
cities inner join shops on cities.id= shops.city_id
inner join vendors on shops.id = vendors.shop_id
where cities.id = (select id from (select cities.id, count(1) from 
cities inner join shops on cities.id= shops.city_id 
inner join vendors on shops.id = vendors.shop_id 
group by cities.id order by 2 desc) limit 1)

【讨论】:

    【解决方案2】:

    如果您运行的是 MySQL 8.0,您可以使用窗口函数来解决这个问题:

    select *
    from (
        select x.*, rank() over(order by cnt) rn
        from (
            select v.*, count(*) over(partition by c.id) cnt
            from cities c
            inner join shops   s on s.city_id = c.id
            inner join vendors v on v.shop_id = s.id
        ) t
    ) t
    where rn = 1
    

    最内部的查询连接三个表,并计算每个城市有多少供应商。下一级按降序排列记录。最后,最后一级过滤排名靠前的行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-22
      • 2020-02-12
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 2018-08-13
      相关资源
      最近更新 更多