GROUP BY 多行并希望显示多于 1 条记录

GROUP BY multiple row and want to show more than 1 record

我有一个storetable,sql是

SELECT * FROM `store` GROUP BY `store_name`, `country`, `branch`

输出为

store_name country branch
store_a US New_York
store_a US Texas
store_b Japan Tokyo
store_c German Hamburg
store_c German Berlin
store_c German Hesse
store_d French Paris

现在我想显示商店有超过 1 个分店

这是我所期望的:

store_name country branch
store_a US New_York
store_a US Texas
store_c German Hamburg
store_c German Berlin
store_c German Hesse

如何实现?

这就是 HAVING 子句的用途。

尝试

SELECT * 
FROM `store` 
GROUP BY `store_name`, `country`, `branch`
HAVING COUNT(*) > 1

加入一个查询,该查询获取每个国家/地区的分支机构数量,并且仅 returns 拥有多个分支机构的分支机构。

SELECT a.*
FROM store AS a
JOIN (
    SELECT store_name, country
    FROM store
    GROUP BY store_name, country
    HAVING COUNT(*) > 1
) AS b ON a.store_name = b.store_name AND a.country = b.country

这是一个使用 window functions 的解决方案(您必须使用 MySQL 8.0 才能使用此功能):

select store_name, country, branch from (
  select store_name, country, branch, 
    count(*) over (partition by store_name) as count
  from store
) as t
where count > 1;

不需要 GROUP BY。