我有一个名为medic_appointment
的表,其中包含以下字段:datetime_diagnosis
(DATETIME
类型)和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
答案 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