MySQL : Selecting the rows with the highest group by count

末鹿安然 提交于 2021-02-11 14:46:24

问题


i have a table with records that are updated every minute with a decimal value (10,2). To ignore measure errors i want to have the number that has been inserted the most. Therefor i tried :

SELECT date_time,max(sensor1),count(ID) FROM `weigh_data` group by day(date_time),sensor1

This way i get the number of records `

Datetime              sensor1    count(ID)
2020-03-19 11:49:12   33.22      3
2020-03-19 11:37:47   33.36      10
2020-03-20 07:32:02   32.54      489
2020-03-20 00:00:43   32.56      891
2020-03-20 14:20:51   32.67      5
2020-03-21 07:54:16   32.50      1
2020-03-21 00:00:58   32.54      1373
2020-03-21 01:15:16   32.56      9
2020-03-22 08:35:12   32.52      2
2020-03-22 00:00:40   32.54      575
2020-03-22 06:50:54   32.58      1

What i actually want is for each day one row wich has the highest count(ID)

Anyone can help me out on this ?


回答1:


With newer MySQL (8.0 and later) you can use the RANK window function to rank the rows according to the count.

Note that this will return all "ties" which means if there are 100 readings of X and 100 readings of Y (and 100 is the max), both X and Y will be returned.

WITH cte AS (
  SELECT 
    DATE(date_time), sensor1,
    RANK() OVER (PARTITION BY DATE(date_time) ORDER BY COUNT(*) DESC) rnk
  FROM `weigh_data` GROUP BY DATE(date_time), sensor1
)
SELECT * FROM cte WHERE rnk=1

If you just want to pick one (non deterministic) of the ties, you can instead use ROW_NUMBER in place of RANK

A DBfiddle to test with.




回答2:


Here is a solution based on a correlated subquery, that works in all versions of MySQL:

select w.*
from weigh_data w
where w.datetime = (
    select w1.datetime 
    from weigh_data w1
    where w1.datetime >= date(w.datetime) and w1.datetime < date(w.datetime) + interval 1 day
    order by sensor1 desc
    limit 1
)

Just like the window function solution using rank(), this allows top ties.

For performance, you want an index on (datetime, sensor1).



来源:https://stackoverflow.com/questions/60798346/mysql-selecting-the-rows-with-the-highest-group-by-count

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!