2
我具備這些表的數據庫:如何有SQL查詢2級的子查詢分爲
- 用戶(ID,電子郵件)
- 旅行(ID,driver_id)
- MatchedTrips(ID,trip_id )
我需要爲每個用戶獲得他創建的旅行總數除以找到的總匹配數。
我一直在爲此構建原始SQL查詢。這是我試過的,並且確定它遠沒有正確。
SELECT
users.email,
total_trips.count1/total_matches.count2
FROM users CROSS JOIN (SELECT
users.email,
count(trips.driver_id) AS count1
FROM trips
INNER JOIN users ON trips.driver_id = users.id
GROUP BY users.email) total_trips
CROSS JOIN (SELECT users.email, count(matches.trip_id) AS count2
FROM matches
LEFT JOIN trips ON matches.trip_id = trips.id
LEFT JOIN users ON trips.driver_id = users.id
GROUP BY users.email) total_matches;
我認爲這個查詢需要處理除零的情況,並且是的電子郵件是唯一的。感謝Gordon的幫助。 –
@IslamWazery。 。 。您的原始查詢不處理這種情況。但很容易:'(count(distinct t.id)/ nullif(count(distinct m.id),0))'。 –
謝謝你,我接受你的答案,因爲它真的是我需要的。 –