[英]MySQL display a count of rows for 2 Group Bys
Sorry in advance, I'm not exactly sure how to explain this but I am trying to do this: 预先抱歉,我不确定该如何解释,但我正在尝试这样做:
I have a table that looks something like this: 我有一张桌子,看起来像这样:
id | make | model
1 | iphone | iphone 7
2 | iphone | iphone 8
3 | iphone | iphone 10
4 | samsung | galaxy note 5
5 | samsung | galaxy note 5
6 | samsung | galaxy note 4
7 | iphone | iphone 7
8 | iphone | iphone 7
9 | htc | one
I want the results to look like this: 我希望结果看起来像这样:
htc | one | 1
iphone | iphone 7 | 3
samsung | galaxy note 5 | 2
So essentially I only want the count for the most rows for each model while grouping both the make and the model. 因此,从本质上讲,我只希望在对品牌和模型进行分组时,每个模型的最多行数。
Hope that makes some sort of sense to someone. 希望这对某人有意义。 Thank you in advance! 先感谢您!
So you want to display the model
with Maximum count for each make
. 因此,您想显示每个make
具有最大数量的model
。
Following query will just do that: 以下查询将做到这一点:
select make,model,count(*) as cnt
from phones p1
group by make,model
having cnt = (select max(p2.cnt)
from
(select make,model,count(*) as cnt
from phones
group by make,model
)p2
where p2.make = p1.make
)
;
Click here for updated DEMO 单击此处获取更新的演示
Hope it helps! 希望能帮助到你!
Do some tricks with mysql functions, you can use substring_index
and group_concat
: 用mysql函数做一些技巧,可以使用substring_index
和group_concat
:
select
`make`,
substring_index(group_concat(`model` order by cnt desc), ',', 1) `model`,
max(cnt) max_count
from (
select `make`, `model`, count(1) cnt
from yourtable
group by `make`, `model`) t
group by `make`
See demo in SQLFiddle. 请参阅SQLFiddle中的演示 。
Some explaination: 一些解释:
t
will query count of each group make
, model
; 子查询t
将查询各组make
, model
; group_concat(model order by cnt desc)
with group by make
will let all model
be concated with separator ,
and order by cnt desc
; 使用group by make
group_concat(model order by cnt desc)
将使所有model
都带有分隔符,
order by cnt desc
; substring_index
is a function which can split string with specified separator and return sub-string according to the index we passed. substring_index
是一个函数,它可以使用指定的分隔符分割字符串并根据我们传递的索引返回子字符串。 All these functions you can check mysql official documents to learn more information. 所有这些功能,您可以查看mysql官方文档以了解更多信息。
You're probably after something like this: 您可能正在执行以下操作:
SELECT a.*
FROM
( SELECT make
, model
, COUNT(*) total
FROM my_table
GROUP
BY make
, model
) a
JOIN
( SELECT make
, MAX(total) total
FROM
( SELECT make
, model
, COUNT(*) total
FROM my_table
GROUP
BY make
, model
) x
GROUP
BY make
) b
ON b.make = a.make
AND b.total = a.total;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.