我试图找到一个MySQL查询,它将在特定字段中找到不同的值,计算该值出现的次数,然后对结果进行排序。
我知道如何处理一行(仅名称1):
SELECT name1, COUNT( * ) AS count
FROM table
GROUP BY name1
ORDER BY `count` ASC
这可能是2行或更多行,还是我需要以前的查询多次?
例子:
id name1 name2
----- ------ ------
1 Mark Paul
2 Mike John
3 Paul Mike
4 Cleo Bert
5 Mike Cleo
6 John Mark
7 Mark Cleo
结果:
names count1 count2
------ ------- ------
Bert 0 1
Cleo 1 2
john 1 1
Mark 2 1
Mike 2 1
Paul 1 1
最佳答案
SELECT name1, COALESCE(sum(count1),0) as count1, COALESCE(sum(count2),0) as count2
FROM
(
select name1, count(*) as count1, null as count2 from your_table group by name1
union all
select name2, null, count(*) from your_table group by name2
) tmp
GROUP BY name1
ORDER BY name1 ASC
关于mysql - 多列计数不同值的出现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29986466/