2013-10-24 40 views
0

幫我請了一些SQL查詢..SQL查詢來比較3個表,並得到回答

我有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查詢得到曾經被劃傷的汽車,並且再次發生事故,當然墜毀的汽車不會出現其他事故。

回答

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; 
+0

差不多!但是這個查詢並沒有返回一個在兩次事故中倖存下來並且在另一個事故中被淹死的車輛......並且它返回的車輛甚至沒有被劃傷...... – kenaku

+0

我認爲你提到你想要以劃傷和意外的方式展示汽車。它應該返回被劃傷的行,因爲我在'results'列上執行'distinct count',該列將計數1和2,並且如果count> 1則汽車被劃傷並且意外。可以發佈一些示例數據或創建[SQL Fiddle](http:// http://sqlfiddle.com/) –