2012-04-17 59 views
0

我是一個業餘人士,只是試圖完成他最後一個他的任務(現在已經過期,只是尋求理解)我坐下來拍攝現在在兩天內嘗試了將近5個小時,並且沒有成功。加入多個表,包括一個表兩次,並通過計算一個組來排序

我已經試過尋找所有不同類型的連接,無法獲得分組工作(永遠),並有排序以及小運氣。我可以一次完成所有這些事情,但這裏的困難在於讓所有這些東西聯合起來。

這是一個問題:

寫SQL查詢來檢索對所有源 - 一個列表(源城,源代碼,目的地城市, 目的地代碼,以及數的-航班)目標至少配對2次。由number_of_flights訂購 。請注意,「航班」表 中的「dest」和「source」屬性均參考「airports」表中的「airportid」。

這裏有我有工作表(也付出了約3000行的虛擬條目)

create table airports (
    airportid char(3)  primary key, 
    city varchar(20) 
); 
create table airlines (
    airlineid char(2)  primary key, 
    name varchar(20), 
    hub char(3)    references airports(airportid) 
); 
create table customers (
    customerid char(10)  primary key, 
    name varchar(25), 
    birthdate date, 
    frequentflieron char(2) references airlines(airlineid) 
); 
create table flights (
    flightid char(6)  primary key, 
    source char(3)   references airports(airportid), 
    dest char(3)   references airports(airportid), 
    airlineid char(2)  references airlines(airlineid), 
    local_departing_time date, 
    local_arrival_time date 
); 
create table flown (
    flightid char(6)  references flights(flightid), 
    customerid char(10)  references customers, 
    flightdate date 
); 

我在同一個查詢運行中被輸出airports.city兩次的第一個問題但結果不同。不僅如此,但不管如何我分組我總是會得到相同的結果時嘗試:

不是一個GROUP BY表達式

通常我有樂趣試圖拼湊這些結合在一起,但這令人沮喪。幫幫我!

+0

請注意,您應該將其標記爲家庭作業。 – Randy 2012-04-17 20:40:58

回答

5
select source.airportid as source_airportid, 
     source.city source_city, 
     dest.airportid as dest_airportid, 
     dest.city as dest_city, 
     count(*) as flights 
from flights 
inner join airports source on source.airportid = flights.source 
inner join airports dest on dest.airportid = flights.dest 
group by 
     source.airportid, 
     source.city, 
     dest.airportid, 
     dest.city 
having count(*) >= 2 
order by 5; 
+0

這工作完美,幾乎正是我正在尋找。我會研究這個,所以我完全理解它,非常感謝你的幫助! – 2012-04-17 21:00:55

+0

下面ericb的子查詢方法更加優化,當航班表比機場表大得多時,其執行速度更快,消耗更少的數據庫資源(CPU,內存等)。 – 2012-04-17 22:09:25

4

您是否嘗試過子查詢?

SELECT source_airports.city, 
     source_airports.airportid, 
     dest_airports.city, 
     dest_airports.airportid, 
     x.number_of_flights 
FROM 
    (
     SELECT source, dest, COUNT(*) as number_of_flights 
     FROM flights 
     GROUP BY source, dest 
     HAVING COUNT(*) > 1 
    ) as x 
    INNER JOIN airports as dest_airports 
    ON dest_airports.airportid = x.dest 
    INNER JOIN airports as source_airports 
    ON source_airports.airportid = x.source 
ORDER BY x.number_of_flights ASC 
+0

+1我喜歡子查詢方法,因爲它將GROUP BY子句限制爲您計算的那些東西(特別是源 - 目標對)。 – 2012-04-17 20:54:26

+0

我確實嘗試過自己構建一些子查詢,但沒有完全理解它們,因此從來沒有工作。感謝您的發佈! – 2012-04-17 21:00:09

+0

@ScottC如果這是作業,你應該看看爲什麼子查詢可能是一個更好的選擇,而不是首先執行所有聯接。子查詢將在聯接發生之前限制記錄,使其成爲可能更便宜的查詢。 – ericb 2012-04-17 21:06:53