如何获得每天的最大记录数?最大(计数)mysql db

ehxuflar  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(329)

很好的一天!
我有一张table:

create table table_1 (field_1 varchar (10),  timestamp datetime(3),  field_2  varchar (10));

日期格式yyyy mm-ddthh:mm:ss.000z。
我需要计算每小时的记录数,得到每天记录数的最大值。
请求:

select date_format(date,'%Y.%m.%d') as date, max(summ)  from (select date_format(timestamp,'%Y.%m.%d %H' ) as date, count(field_2) as summ from table_1 a where field_1 in (1) group by date) b group by date;

结果:

date        summ
2019.12.25  2
2019.12.25  3
2019.12.25  12

但我需要这样的东西:

date        summ
2019.12.25  12
2019.12.26  15
2019.12.27  14
tvmytwxo

tvmytwxo1#

将窗口函数用于聚合:

select t.*
from (select date_format(timestamp, '%Y.%m.%d %H') as date, count(field_2) as summ,
             row_number() over (partition by date(timestamp) order by count(field_2) desc) as seqnum
      from table_1 a
      where field_1 in (1)
      group by date, date(timestamp)
     ) t
where seqnum = 1;

下面是代码正确运行的演示。

相关问题