2013-04-02 18 views
5

tôi có hai bảng Incident (id, ngày) Reminder (incidentID, type) bên tham gia vào incident.id = reminder.incidentIDSQL chọn nếu đếm

và tôi muốn tận incident.id chỉ khi nó đã có hơn 4 reminder.type = 15 những gì tôi nghĩ là

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

Các erroe tôi nhận được là

Dòng 6: cú pháp sai gần ' = '.

Tôi có thể làm gì?

Trả lời

1

Bạn đang gần:

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 

cú pháp ban đầu của bạn sẽ không hoạt động trong hầu hết các phương ngữ của SQL. Bạn cần tập hợp có điều kiện.

2

mệnh đề group by nên được tuyên bố trước having khoản

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

COUNT không hoạt động như thế.

Hãy thử:

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 nhưng tôi tin rằng nó là thực hành tốt (thậm chí theo yêu cầu của hầu hết các DBMS) để có GROUP BY trước HAVING – Najzero