0

请帮我一些sql查询..

我有 3 张桌子:

CREATE TABLE cars (
    id integer not null primary key,  -- id of car
    name text not null, -- car name
)

——事故

CREATE TABLE accidents (
    id integer not null primary key, -- id of accident
    place text not null, -- place of accident
    a_date date not null -- date of accident
)

——事故结果

CREATE TABLE outcomes (
    car_id integer not null, -- id of car
    accident_id integer not null, -- id of accident
    result smallint not null, -- result: 0 - fine, 1 - scratched, 2 - crashed
    CONSTRAINT outcomes_pkey PRIMARY KEY (car_id, accident_id)
)

我需要一个 sql 查询来获取被划伤一次的汽车,而不是再次发生事故,当然坠毁的汽车不能发生其他事故。

4

1 回答 1

0

尝试这个

select c.id, c.name, count(distinct o.results) cnt
from cars c
inner join outcomes o on c.id = o.car_id
where o.results in (1,2)
group by c.id, c.name
having count(distinct o.results) > 1;
于 2013-10-24T13:19:38.287 回答