謝謝你幫我,我還在學習 SQL。我有一個名為 JEDI 的主表,我正在嘗試獲取有關使用 Inner JOIN 和Where 條件的具體資訊。具體來說,我希望獲得在特定日期之間訪問特定星球的 JEDI 數量及其等級。
然後我想在同一張表上使用 Inner JOIN 進行過濾,並僅向我顯示在該特定星球上擁有超過 1 個 padawan 的 JEDI 的結果。我認為第二個條件讓我失望。我已經貼上了我使用過的程式碼和範例資料表
我的結果應該只是2,歐比王大師是他唯一符合標準的
SELECT COUNT(jedi.jedi_id),jedi.rank_id FROM jedi WHERE jedi.date >='2022-01-01' AND jedi.date <='2022-06-31' AND jedi.planet='Tatoine' INNER JOIN jedi ON jedi.jedi_id WHERE COUNT(jedi.padawan)>=2 GROUP BY jedi.rank_id
P粉8785105512024-02-04 16:59:14
首先,您需要對列進行分組並使用 HAVING COUNT
來計算重複值。
SELECT COUNT(jedi.jedi_id),jedi.rank_id FROM jedi WHERE jedi.date BETWEEN '2022-01-01' AND '2022-06-31' AND jedi.planet='Tatoine' GROUP BY jedi.jedi_id, jedi.rank_id HAVING COUNT(jedi.jedi_id) > 1
注意:僅當每個 jedi_id
具有唯一值 jedi.padawan
時,此功能才有效。此查詢適用於這些場景。
但是,您可以透過新增另一個計算唯一jedi.padawan
的條件來改進查詢,以便每個jedi.jedi_id< 上重複出現< 上重复出现
jedi.padawan
#值/code> 不會被包含
SELECT COUNT(jedi.jedi_id),jedi.rank_id FROM jedi WHERE jedi.date BETWEEN '2022-01-01' AND '2022-06-31' AND jedi.planet='Tatoine' GROUP BY jedi.jedi_id, jedi.rank_id HAVING COUNT(jedi.jedi_id) > 1 AND COUNT (DISTINCT jedi.padawan) > 1
P粉2486022982024-02-04 14:18:54
您可以使用必須替換此 INNER JOIN jedi ON jedi.jedi_id WHERE COUNT(jedi.padawan)>=2