根据每个组中另一列中的最大值查找一列的值

时间:2017-12-07 13:11:16

标签: mysql

我有一个查询,它给了我三列:一个ID,一周的事件日和一周中每天有多少事件的数量,即

ID    Day_Name    Cnt
1     Thursday    1
2     Monday      3
2     Thursday    2
2     Sunday      2
3     Tuesday     7
3     Wednesday   3

我通过使用查询

得到这个
SELECT P.ID, DAYNAME(E.EVENT_DATE) AS Day_Name, COUNT(*) AS Cnt
FROM EVENT AS E

INNER JOIN PERSON AS P
ON P.ID_2 = E.ID_2

WHERE E.EVENT_DATE > '2016-01-01'
AND E.EVENT_STATUS LIKE '%OCCURED%'

GROUP BY P.ID, DAYNAME(E.EVENT_DATE)

我想将此查询减少为仅返回具有最大计数的每个用户的星期几。同时,我想用计数更改列,而不是显示该工作日的事件频率。对于上面的示例,我想将输出更改为

ID    Day_Name    Frequency
1     Thursday    1
2     Monday      0.429
3     Tuesday     0.7

感谢任何人有个主意

2 个答案:

答案 0 :(得分:1)

要获得预期的结果集,您可以在外部查询中进行计算,例如

SELECT ID,
SUBSTRING_INDEX(GROUP_CONCAT(Day_Name ORDER BY Cnt DESC),',',1) Day_Name,
MAX(Cnt)/SUM(Cnt) Frequency
FROM(
    SELECT P.ID, DAYNAME(E.EVENT_DATE) AS Day_Name, COUNT(*) AS Cnt
    FROM EVENT AS E
    INNER JOIN PERSON AS P
    ON P.ID_2 = E.ID_2
    WHERE E.EVENT_DATE > '2016-01-01'
    AND E.EVENT_STATUS LIKE '%OCCURED%'
    GROUP BY P.ID, DAYNAME(E.EVENT_DATE)
) t
GROUP BY ID

答案 1 :(得分:1)

所以这是一个部分答案......

SELECT a.*
  FROM ([your query here]) a
  JOIN 
     ( SELECT id,MAX(cnt) cnt FROM ([your query here]) GROUP BY id ) b
    ON b.id = a.id
   AND b.cnt = a.cnt;

有关更完整的答案,我建议您提供原始的18行数据集。请参阅:Why should I provide an MCVE for what seems to me to be a very simple SQL query?