SQL SUM operation of multiple subqueries

后端 未结 6 809
清歌不尽
清歌不尽 2021-01-12 09:52

i have the following mysql database table designed,

ticket(id, code, cust_name);
passenger(id, ticket_id, name, age, gender, fare);
service(id, passenger_id,         


        
6条回答
  •  清酒与你
    2021-01-12 10:43

    How about this?

    with fares as(
    select p.id id, p.ticket_id ticket_id, sum(coalesce(s.cost,0)) cost
      from passenger p left outer join service s
           on p.id = s.passenger_id
     group by p.id, p.ticket_id)
    select q.ticket_id, sum(f.cost), sum(q.fare), sum(f.cost + q.fare)
      from fares f inner join passenger q
           on f.id = q.id
     group by q.ticket_id;
    

提交回复
热议问题