复杂SQL查询:添加求和列

时间:2013-11-29 09:57:47

标签: sql sum

我有一个查询创建了我正在寻找的表,但一个字段除外。我想添加一个总和列,我不知道在哪里添加:

SUM(b.requested_seats)声明。

以下是查询:

SELECT COUNT(*) as rep_cnt, *
FROM (SELECT r.id AS r_id,
             b.state,
             l1.idl AS lidl1,
             l1.query AS lstart_name,
             l1.latitude AS lstart_lat,
             l1.longitude AS lstart_long,
             l2.idl AS lidl2,
             l2.query AS lend_name,
             l2.latitude AS lend_lat,
             l2.longitude AS l_end_long,

(SELECT location_id FROM waypoints WHERE ride_id = r.id ORDER BY position ASC LIMIT 1) AS start_point,
(SELECT location_id FROM waypoints WHERE ride_id = r.id ORDER BY position DESC LIMIT 1) AS end_point
       FROM bookings AS b, rides AS r, locations AS l1, locations AS l2
       WHERE b.state = 'accepted'
       AND b.ride_id = r.id) AS sub
       WHERE lidl1 = start_point
       AND lidl2 = end_point
       GROUP BY sub.r_id, sub.state, sub.start_point, sub.end_point, sub.lidl1,      sub.lstart_lat, sub.lstart_long, sub.lidl2, sub.lend_lat, sub.lend_long, sub.lstart_name, sub.lend_name;

有没有人知道如何从预订表中插入求和列?

1 个答案:

答案 0 :(得分:0)

你有没有试过这个?

SELECT COUNT(*) as rep_cnt, SUM(sub.requested_seats) , *
FROM (SELECT r.id AS r_id,
             b.state,
             b.requested_seats,
             l1.idl AS lidl1,
             l1.query AS lstart_name,
             l1.latitude AS lstart_lat,
             l1.longitude AS lstart_long,
             l2.idl AS lidl2,
             l2.query AS lend_name,
             l2.latitude AS lend_lat,
             l2.longitude AS l_end_long,

(SELECT location_id FROM waypoints WHERE ride_id = r.id ORDER BY position ASC LIMIT 1) AS start_point,
(SELECT location_id FROM waypoints WHERE ride_id = r.id ORDER BY position DESC LIMIT 1) AS end_point
       FROM bookings AS b, rides AS r, locations AS l1, locations AS l2
       WHERE b.state = 'accepted'
       AND b.ride_id = r.id) AS sub
       WHERE lidl1 = start_point
       AND lidl2 = end_point
       GROUP BY sub.r_id, sub.state, sub.start_point, sub.end_point, sub.lidl1,      sub.lstart_lat, sub.lstart_long, sub.lidl2, sub.lend_lat, sub.lend_long, sub.lstart_name, sub.lend_name;