簡體   English   中英

如何獲得每天的最大記錄數? 最大(計數) MySQL DB

[英]How to get maximum number of records per day? max(count) MySQL DB

再會!

我有一張桌子:

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

您可以將 window 函數與聚合一起使用:

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;

是代碼正確運行的演示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM