SQL:如何制作多个COUNT / MAX

时间:2016-11-23 11:10:31

标签: mysql

我有一个名为medic_appointment的表,其中包含以下字段:datetime_diagnosisDATETIME类型)和diagnosis。我需要执行一个查询,向我显示每种疾病发生次数最多的YEAR_MONTH

我目前正处于这一点:

SELECT disease , COUNT(*) AS frequency , 
       EXTRACT(YEAR_MONTH FROM datetime_diagnosis) AS interval
FROM medic_appointment
GROUP BY disease , interval

这导致以下示例表:

disease    frequency   interval
--------   ---------   --------
disease1   5           201609
disease1   8           201610
disease1   22          201611
disease1   1           201612
disease2   7           201611

我正在尝试做这样的事情:使用上面提到的查询,以一种选择最高频率数字的方式递增它并返回间隔和疾病字段,然后按疾病分组...但它是不这样工作,我只是找不到另一种解决方法。不确定这是否是最佳选择。

编辑:预期结果:

disease    frequency   interval
--------   ---------   --------
disease1   22          201611
disease2   7           201611

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT disease, frequency, interval
FROM (
  SELECT disease, frequency, interval,
         @rnk := IF(@dis = disease, @rnk + 1,
                    IF(@dis := disease, 1, 1)) AS rnk  
  FROM (
     SELECT disease, COUNT(*) AS frequency, 
            EXTRACT(YEAR_MONTH FROM datetime_diagnosis) AS interval
     FROM medic_appointment
     GROUP BY disease, interval) AS t
  CROSS JOIN (SELECT @rnk := 0, @dis := '') AS vars
  ORDER BY disease, frequency DESC) AS x
WHERE x.rnk = 1