1

伙计们,我想从下表中获取特定年份的前 3 种疾病以及它们的计数。我应该运行什么查询?

mysql> select id,dname,d_id,entrydate from patient_master;    
+----+------------------+------+------------+    
| id | dname            | d_id | entrydate  |     
+----+------------------+------+------------+          
|  1 | Root Canal       |    1 | 2012-08-02 |         
|  2 | Cosmetic Filling |    3 | 2012-05-10 |   
|  3 | Root Canal       |    1 | 2012-05-25 |   
|  4 | High BP          |    6 | 2012-07-09 |    
|  5 | Root Canal       |    1 | 2012-07-10 |      
|  6 | Normal Filling   |    2 | 2012-05-10 |     
|  7 | Maleria          |    4 | 2012-07-10 |    
|  8 | Maleria          |    4 | 2012-07-12 |    
|  9 | Typhoid          |    5 | 2012-07-12 |    
+----+------------------+------+------------+    
9 rows in set (0.00 sec)
4

2 回答 2

2

使用group by子句按疾病组合结果,并count(*)统计每种疾病的记录数。然后,您可以从最大到最小排序,并使用limit 3它只获得前 3 个。我还包括一个where子句,用于仅过滤2012.

  select count(*), dname
    from patient_master
   where entrydate between '2012-01-01' and '2013-01-01'
group by dname
order by count(*) desc
   limit 3

演示:http ://www.sqlfiddle.com/#!2/89c06/6

于 2012-07-23T18:41:43.123 回答
0
SELECT d_id, dname, count(d_id) as `count`, year(entrydate) as `year`
FROM patient_master
GROUP by `year`, d_id
ORDER BY `year` DESC, `count` DESC

注意我没有在这里设置限制,好像你想在同一个查询中同时获得年份和计数,你需要编写一个非常复杂的查询来获得每年的前 3 名。

这将按年份降序排序,然后按每年内的疾病计数降序排序。您将注意到能够在此查询中获取行 id,而且您也不应该关心该值,因为您正在尝试执行此操作。

于 2012-07-23T18:47:01.833 回答