我有以下查詢:SQL max函數
SELECT q.category_id as Category_id , COUNT(q.question_id) as count
from questions as q
INNER JOIN interestingQuestion as i using (question_id)
group by q.category_id
這是給我下面的結果 - 就像我需要根據我在我的表中的數據:
Category_id Count
5 1
6 3
現在我需要找到具有最高計數器CATEGORY_ID,所以我做了以下查詢:
SELECT t.Category_id, MAX(t.Count)
from(
SELECT q.category_id as Category_id , COUNT(q.question_id) as count
from questions as q INNER JOIN interestingQuestion as i using (question_id)
group by q.category_id
)as t
和那我得到的結果是:
category_id MAX(t.count)
5 3
這是一個混合起來的結果,它的發現最大計數器,但它給我一個錯誤的CATEGORY_ID
爲什麼會發生?我該如何解決它?
Tnx!這是行之有效的,是否有可能通過這種方式返回一些結果(所有結果都與MAX相同)(不知道有多少結果)? – 2013-05-05 15:22:59
@ShaiZarzewski我已經更新了我的答案,現在應該沒問題! – fthiella 2013-05-05 15:28:22
太棒了!它的工作很好,只需在最後一行之前的最後一行添加「as」,以便它能夠工作 – 2013-05-05 15:41:04