我只想显示具有相同GROUP_CONCAT()列值的行。最后使用GROUP BY时,由于GROUP BY国家的原因,它仅在表中显示姓氏。当我按国家/地区分组时,是否仍然可以显示所有行? 这是我的SQL:
SELECT firstname, lastname, country, COUNT(*) c
FROM (
SELECT firstname, lastname,
GROUP_CONCAT(
DISTINCT f.countryname
ORDER BY f.countryname ASC
SEPARATOR ','
) AS country
FROM person p
INNER JOIN favoritecountry f
ON p.id = f.id
GROUP BY firstname, lastname
) t
GROUP BY country
HAVING c > 1
ORDER BY c DESC;
我的结果是:
+-----------+----------+--------------+---+
| firstname | lastname | country | c |
+-----------+----------+--------------+---+
| bill | smith | Poland,Spain | 2 |
+-----------+----------+--------------+---+
相反,我想要这样的东西:
+-----------+----------+--------------+---+
| firstname | lastname | country | c |
+-----------+----------+--------------+---+
| bill | smith | Poland,Spain | 2 |
| phil | cooper | Poland,Spain | 2 |
+-----------+----------+--------------+---+
SQL新手,所以需要一些帮助
答案 0 :(得分:1)
根据您的预期结果,您应该将group_concat国家/地区的计数与国家/地区的名称交叉加入
select t2.firstname, t2.lastname, t2.country
from (
SELECT firstname, lastname,
GROUP_CONCAT(
DISTINCT f.countryname
ORDER BY f.countryname ASC
SEPARATOR ','
) AS country
FROM person p
INNER JOIN favoritecountry f
ON p.id = f.id
GROUP BY firstname, lastname
) t2
cross join (
select t1.country, count(*) my_count
from (
SELECT firstname
, lastname,
GROUP_CONCAT( DISTINCT f.countryname
ORDER BY f.countryname ASC
SEPARATOR ','
) AS country
FROM person p
INNER JOIN favoritecountry f ON p.id = f.id
GROUP BY firstname, lastname
) t
) t1 on t1.country = t2.country
答案 1 :(得分:0)
从MySQL 8开始,您可以将窗口函数(例如COUNT OVER
)用于此类任务:
SELECT firstname, lastname, countries, cnt
FROM
(
SELECT firstname, lastname, countries, COUNT(*) over (PARTITION BY countries) AS cnt
FROM
(
SELECT
p.firstname, p.lastname,
GROUP_CONCAT(DISTINCT f.countryname
ORDER BY f.countryname ASC
SEPARATOR ',') AS countries
FROM person p
INNER JOIN favoritecountry f ON p.id = f.id
GROUP BY p.firstname, p.lastname
) grouped
) counted
WHERE cnt > 1
ORDER BY cnt DESC, countries;