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

时间:2018-10-18 18:00:28

标签: mysql sql

我有一个表,其中包含正在使用的两列测试数据:“日期”和“象限”。象限列是一个包含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

以下是指向表和所有右上角数据的链接:https://rextester.com/UQDSB56921

1 个答案:

答案 0 :(得分:0)

您可以检查this post来查看完成此操作的不同方法(在MySQL中获得argmax

一种方法(在注释中提到)是自抗联接:

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