我有两张桌子:
DRIVER(Driver_Id,First name,Last name,...);
PARTICIPANT IN CAR ACCIDENT(Participant_Id,Driver_Id-foreign key,responsibility-yes or no,...).
现在,我需要找出哪个司机参与了事故,责任是'是',以及多少次。我这样做了:
Select Driver_ID, COUNT (Participant.Driver_ID)as 'Number of accidents'
from Participant in car accident
where responsibility='YES'
group by Driver_ID
order by COUNT (Participant.Driver_ID) desc
但是,我需要从第一个表中添加驱动程序的名字和姓氏(我猜想使用内部联接)。我不知道如何,因为它不包含在聚合函数或GROUP BY子句中。 请帮助:)
答案 0 :(得分:1)
如您所料,您需要使用内部联接。并且因为名字和姓氏现在是SELECT的一部分,所以您还需要在GROUP BY中包含这些列。
Select Driver_ID, First_name, Last_name COUNT (Participant.Driver_ID) as "Number of accidents"
from "Participant in car accident" join Driver on "Participant in car accident".Driver_ID = Driver.Driver_ID
where responsibility='YES'
group by Driver_ID, First_name, Last_name
order by COUNT (Participant.Driver_ID) desc
这是家庭作业吗?
答案 1 :(得分:0)
您可以使用内联表:
SELECT d.driver_first_name,
d.driver_last_name,
r.incident_count
FROM DRIVER d
INNER JOIN (SELECT driver_id,
count(*) incident_count
FROM PARTICIPANT_IN_CAR_ACCIDENT
WHERE responsibility = 'YES'
GROUP BY driver_id) r
ON d.driver_id = r.driver_id
ORDER BY r.incident_count DESC
应该工作。