2012-07-23 50 views
1

夥計們我想得到前3名疾病,也從他們的計數從下表特定年份..我應該運行什麼查詢?從數據庫中獲取最大(頂部的東西數據)在mysql

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) 
+2

您可能會發現瀏覽[** SQLCourse **](http://www.sqlcourse.com/index.html)等在線教程很有幫助,因爲這是一個非常簡單的標準查詢。 – mellamokb 2012-07-23 18:44:29

回答

2

使用group by條款通過疾病的結果結合起來,並count(*)計數的每種疾病的記錄數。然後,您可以從最大到最小的順序排列,並使用limit 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

+1

你可能想'將年份(entrydate)= 2012'更改爲'entrydate BETWEEN'2012-01-01'和'2012-12-31''以防萬一他有幾百萬行;) – Vatev 2012-07-23 18:44:21

+0

@Vatev:好點子。由於假設'00:00:00'的日期比較,我將您的建議結束日期更改爲'2013-01-01'# – mellamokb 2012-07-23 18:46:55

+0

哥們我能在這裏得到每一個月的月數嗎?實際上我想要這個融合折線圖。 – 2012-07-23 19:09:30

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,你也不應該在乎你想要做的事情。

相關問題