2015-12-16 80 views
0

我有以下代碼:HAVING MAX(COUNT(*))不工作

SELECT e.Student_ID, s.Name, s.Surname, Result_IS, COUNT(*) 
FROM Students s 
LEFT JOIN Exams e 
    ON e.Student_ID=s.Student_ID 
WHERE Result_IS='Negative' 
GROUP BY e.Student_ID, s.Name, s.Surname, Result_IS 
HAVING COUNT(*)= 
(
    SELECT MAX(COUNT(*)) FROM Exams 
    WHERE Student_ID=e.Student_ID 
    AND Result_IS='Negative' 
    GROUP BY e.Student_ID, s.Name, s.Surname, Result_IS 
) 

我在與HAVING COUNT(*)應選擇其中COUNT(*)給了最大的結果行的問題,而是它只是給我的第一選擇的輸出,這是以下幾點:

The output

我一直在嘗試所有種類的東西,但沒有什麼工作,選擇該行,其中數是最大的。

只要給我一個提示,請問我應該從哪裏開始走,以及代碼有什麼問題。

回答

1

爲什麼不按數量(*)desc排序並選擇top 1?

SELECT top 1 e.Student_ID, s.Name, s.Surname, Result_IS, COUNT(*) FROM Students s LEFT JOIN Exams e 
ON e.Student_ID=s.Student_ID 
WHERE Result_IS='Negative' 
GROUP BY e.Student_ID, s.Name, s.Surname, Result_IS 
order by count(*) desc 

我覺得這是O​​racle

語法
Select * FROM 
    (
      SELECT e.Student_ID, s.Name, s.Surname, Result_IS, COUNT(*) FROM Students s LEFT JOIN Exams e 
      ON e.Student_ID=s.Student_ID 
      WHERE Result_IS='Negative' 
      GROUP BY e.Student_ID, s.Name, s.Surname, Result_IS 
      order by count(*) desc 
) 
    Where rownum=1 
+1

謝謝,但我已經知道這個方法,我不希望做這種方式。順便說一下,在此期間,我想出瞭如何去做。但是,無論如何感謝:) –

+0

你應該在這裏發佈你的答案爲社區。 – Wjdavis5

+1

PL/SQL是Oracle的過程語言。你可能打算說「Oracle SQL」。而對於Oracle來說,在同一個查詢中,你必須注意將'rownum'和'order by'混合在一起,因爲'rownum'過濾器在'order by'之前被應用*,所以結果將不正確。相反,你會想要像這樣的:'select * from(subquery-with-order-by)where rownum = 1'。 – sstan

1

請在連接表

HAVING COUNT(*)= 
(
SELECT MAX(COUNT(*)) FROM Exams 
WHERE Student_ID=e.Student_ID 
AND Result_IS='Negative' 
GROUP BY e.Student_ID, s.Name, s.Surname, Result_IS 
) 

查詢。 :)

0

所以,我發現瞭如何做到這一點,解決方法如下:

SELECT e.Student_ID, s.Name, s.Surname, Result_IS, COUNT(*) FROM Students s LEFT JOIN Exams e 
ON e.Student_ID=s.Student_ID 
WHERE Result_IS='Negative' 
GROUP BY e.Student_ID, s.Name, s.Surname, Result_IS 
HAVING COUNT(*)= 
(
SELECT MAX(count) from 
(
SELECT count(*) as count FROM Exams 
WHERE Result_Is='Negative' 
GROUP BY Student_ID 
) 
)