查找给定工作日的最大出现次数

y3bcpkx1  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(274)

我有一个包含测试数据的表,其中有两列我正在处理:“date”和“quadrant”。象限列是包含4个可能值(1、2、3或4)的枚举值。
一周中的每一天(日期为4个月)都有一个与之关联的枚举值。
枚举值在任何给定的一天中定期出现几次。
我试图计算出整个表中给定工作日象限枚举值最常见的出现次数。
例如,周一有20个枚举值为“1”,19个值为“2”。
我只想看看最常见的,在这个例子中是“1”。
像这样:

Monday.........1
Tuesday........3
Wednesday......4
Thursday.......1
Friday..........2

到目前为止,我已经尝试了以下方法,但它只给出象限列在每个工作日具有枚举值的总次数。

SELECT DAYNAME(Date) AS Weekday
     , COUNT(quadrant) AS 'Most Likey Damaged Quadrant' 
  FROM damage_tbl 
 WHERE quadrant IS NOT NULL 
 GROUP 
    BY quadrant 
 ORDER
    BY WEEKDAY

以下是该表和rextester上所有数据的链接:https://rextester.com/uqdsb56921

ewm0tg9j

ewm0tg9j1#

你可以查看这篇文章,看看实现这一点的不同方法(获取 argmax 在mysql中)
其中一种方法(在评论中提到)是自反连接:

SELECT a.Weekday, a.quadrant FROM (
    SELECT DAYNAME(Date) AS Weekday, quadrant, COUNT(*) AS 'cnt' 
      FROM damage_tbl 
     WHERE quadrant IS NOT NULL 
     GROUP 
        BY WEEKDAY, quadrant
     ORDER
        BY WEEKDAY, count(*) desc ) a LEFT JOIN (
    SELECT DAYNAME(Date) AS Weekday, quadrant, COUNT(*) AS 'cnt' 
      FROM damage_tbl 
     WHERE quadrant IS NOT NULL 
     GROUP 
        BY WEEKDAY, quadrant
     ORDER
        BY WEEKDAY, count(*) desc ) b 
ON a.Weekday = b.Weekday and a.cnt < b.cnt  
WHERE b.Weekday is null

相关问题