gpt4 book ai didi

MySQL语句-从一组中选择最大值

转载 作者:可可西里 更新时间:2023-11-01 07:45:05 24 4
gpt4 key购买 nike

您好,我有下表,我想选择每个月插入的最大值(计数(*))。 sqlfiddle.com/#!2/13036/1

select * from broadcast

profile, plugged, company, tstamp
1, 2, 1, 2013-10-01 08:20:00
1, 3, 1, 2013-10-01 08:20:00
2, 1, 1, 2013-10-01 08:20:00
2, 3, 1, 2013-10-01 08:20:00
3, 1, 1, 2013-10-01 08:20:00
3, 1, 1, 2013-09-01 08:20:00

所以如果我做类似下面的事情:

    select plugged, 
count(*),
extract(month from tstamp),
extract(year from tstamp)
from broadcast
where company=1
group by plugged,
extract(month from tstamp),
extract(year from tstamp)
order by count(*) desc;

输出:

plugged, count(*), extract(month from tstamp), extract(year from tstamp)
3, 2, 10, 2013
1, 2, 10, 2013
2, 1, 10, 2013
1, 1, 9, 2013

期望的输出:

plugged, count(*), extract(month from tstamp), extract(year from tstamp)
3, 2, 10, 2013
1, 2, 10, 2013
1, 1, 9, 2013

这是对的...但我只想要 max(count(*)) (例如在这种情况下仅第一行)。可能存在 2 行具有最大计数的情况,但对于每个月/年,我只想返回最大计数行...我是否需要内部选择语句或其他内容?

最佳答案

试试这个

 select plugged, max(counts) counts, month , year
from
(select plugged ,count(*) as counts ,extract(month from tstamp) month , extract(year from tstamp) year from broadcast where company=1
group by plugged,month ,year order by counts desc ) as x ;

关于MySQL语句-从一组中选择最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19105023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com