2013-09-28 199 views
-1

我一直在嘗試幾個小時來解決網頁中的練習(自學sql),但我無法正確執行練習。SQL:高級查詢

This is the summary

這是我走到這一步,

SELECT p.name, COUNT(trip_no) 
FROM Pass_in_trip AS pit 
INNER JOIN (
    SELECT r.seat as seat, MAX(r.qty) as qty 
    FROM (
     SELECT place AS seat, COUNT(trip_no) AS qty 
     FROM Pass_in_trip 
     INNER JOIN (
      SELECT place AS seat 
      FROM Pass_in_trip 
      GROUP BY place 
      HAVING COUNT(ID_psg) > 1 
     ) AS s 
     ON s.seat = place 
     GROUP BY ID_psg, place 
    ) as r 
    GROUP BY r.seat 
    HAVING MAX(r.qty) > 1 
) as r 
ON place = r.seat 
INNER JOIN Passenger AS p 
ON p.ID_psg = pit.ID_psg 
GROUP BY p.name, p.ID_psg, place, r.qty 
HAVING COUNT(trip_no) = r.qty 

/* This query gives better results than the previous one, however, 
it doesn't pass all tests */ 

SELECT p.name, COUNT(trip_no) 
FROM Pass_in_trip AS pit 
INNER JOIN (
    SELECT r.seat as seat, MAX(r.qty) as qty 
    FROM (
     SELECT place AS seat, COUNT(trip_no) AS qty 
     FROM Pass_in_trip 
     GROUP BY ID_psg, place 
    ) as r 
    GROUP BY r.seat 
    HAVING MAX(r.qty) > 1 
) as r 
ON place = r.seat 
INNER JOIN Passenger AS p 
ON p.ID_psg = pit.ID_psg 
GROUP BY p.name, r.qty 
HAVING COUNT(trip_no) = r.qty 

一些幫助將非常感激查詢。 此致敬禮。

回答

1

嘗試

SELECT p.name, COUNT(trip_no) 
FROM Pass_in_trip AS pit 
INNER JOIN (
    SELECT r.seat as seat, MAX(r.qty) as qty 
    FROM (
     SELECT place AS seat, COUNT(trip_no) AS qty 
     FROM Pass_in_trip 
     INNER JOIN (
      SELECT place AS seat 
      FROM Pass_in_trip 
      GROUP BY place 
      HAVING COUNT(ID_psg) > 1 
     ) AS s 
     ON s.seat = place 
     GROUP BY ID_psg, place 
    ) as r 
    GROUP BY r.seat 
    HAVING MAX(r.qty) > 1 
) as r 
ON place = r.seat 
INNER JOIN Passenger AS p 
ON p.ID_psg = pit.ID_psg 
GROUP BY p.name,trip_no 
HAVING COUNT(trip_no) = r.qty 
+0

我得到一個錯誤,因爲r.qty沒有在GROUP BY子句包括在內。我覺得我越來越近,但我不能 –

+0

再試一次,只是修改了 – sunysen

+0

它既不工作也不工作,我得到同樣的錯誤。 'r.qty'正在HAVING中使用,因此它需要包含在GROUP BY子句中。 –