2013-04-02 12 views
5

ho due tavole Incident (id, data) Promemoria (incidentID, tipo) inner join su incident.id = reminder.incidentIDSQL selezionare se contare

e voglio prendere incident.id solo se ha più di 4 reminder.type = 15 quello che penso è

SELECT incident.id 
FROM incident 
INNER JOIN reminder ON incident.id = reminder.incidentid 
HAVING COUNT (reminder.remindertype = "something") >5 
GROUP BY incident.incidentcode 

L'erroe che ottengo è

linea 6: la sintassi non corretta in prossimità ' ='.

Cosa posso fare?

risposta

1

Vi sono vicino:

select incident.id 
from incident inner join 
    reminder 
    on incident.id = reminder.incidentid 
group by incident.incidentcode 
having sum(case when reminder.remindertype = "something" then 1 else 0 end) >5 

la sintassi originale non avrebbe funzionato nella maggior parte dei dialetti di SQL. Hai bisogno dell'aggregazione condizionale.

2

la clausola group by dovrebbe essere dichiarare prima having clausola

select incident.id 
from incident 
inner join reminder 
on incident.id = reminder.incidentid 
group by incident.incidentcode 
having count (reminder.remindertype) >5 
2

COUNT non funziona così.

Prova:

select incident.id 
from incident 
inner join reminder 
on incident.id = reminder.incidentid 
WHERE reminder.remindertype = "something" 
group by incident.incidentcode 
having count (reminder.remindertype) >5 
+0

+1, ma credo che sia buona pratica (anche richiesto da più DBMS) per avere la GROUP BY prima di aver – Najzero