如何将 SQL 查询分成 2 个子查询

How to have SQL query with 2 subqueries divided

我有一个包含这些表的数据库:

  1. 用户(ID、电子邮件)
  2. 行程(id,driver_id)
  3. 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;

您可以按如下方式计算每个 driver 的总行程和总匹配数:

select driver_id, count(t.id) as total_trips, count(m.id) as total_matches
from trips t
left join matches m on (t.id = trip_id)
group by 1

使用此查询作为派生的 table 与 users:

连接
select email, total_trips, total_matches, total_trips::dec/ nullif(total_matches, 0) result
from users u
left join (
    select driver_id, count(t.id) as total_trips, count(m.id) as total_matches
    from trips t
    left join matches m on (t.id = trip_id)
    group by 1
    ) s on u.id = driver_id
order by 1;

SQLFiddle.

最简单的方法可能是使用count(distinct):

select u.email,
       count(distinct t.id) as num_trips,
       count(distinct m.id) as num_matches,
       (count(distinct t.id) / count(distinct m.id)) as ratio
from users u left join
     trips t
     on t.driver_id = u.id left join
     matches m
     on m.trip_id = t.trip_id
group by u.email;

注意:如果邮箱是唯一的,那么可以简化查询。 count(distinct) 在某些情况下可能会很昂贵。