我正在尝试加入2个表,其中id是相同的,但在同一个查询中,我试图得到2列的总和然后按ID分组?
我尝试了很多不同的查询,但他们都失败了,或者没有给我我需要的结果。
这是我到目前为止所处的位置:
SELECT *
FROM tour_detail, SUM(Payment_Amount) AS amount1, SUM(trip_cost) AS amount2 FROM bookings INNER JOIN bookings ON tour_detail.tour_id=bookings.tour_id GROUP BY tour_detail.tour_id
编辑...
表:tour_detail
tour_id | tour_title | start_date | rates | child_rate | fully_booked
----------------------------------------------------------------------
29 | Title 1 | 2017-08-17 | 3.00 | 0.50 | 0
31 | Title 2 | 2017-08-22 | 4.50 | 1.50 | 0
表:预订
tour_id | adults | childs | Payment_Amount | trip_cost
----------------------------------------------------------------------
29 | 3 | 0 | 0.00 | 9.00
31 | 5 | 2 | 13.00 | 26.00
29 | 2 | 1 | 3.25 | 6.50
我想列出所有旅行,并显示预订了多少成人和儿童。我还想显示每次旅行的总payment_amount和总trip_cost。
所以我希望我的结果看起来像这样(道歉,如果这不能正确,这是我第一次在这里发布代码)
tour_id | tour_title | start_date | rates | child_rate | fully_booked | adults | childs | amount1 | amount2
----------------------------------------------------------------------------------------------------------------------------------
29 | Trip title 1 | 2017-08-17 | 3.00 | 0.50 | 0 | 5 | 1 | 3.25 | 15.50
31 | Trip title 2 | 2017-08-22 | 4.50 | 1.50 | 0 | 5 | 2 | 13.00 | 26.00
答案 0 :(得分:0)
您可以尝试在单独的子查询中计算总和,然后加入:
SELECT
t1.*,
t2.adults,
t2.childs,
t2.amount1,
t2.amount2
FROM tour_detail t1
INNER JOIN
(
SELECT
tour_id,
SUM(adults) AS adults,
SUM(childs) AS childs,
SUM(Payment_Amount) AS amount1,
SUM(trip_cost) AS amount2
FROM bookings
GROUP BY tour_id
) t2
ON t1.tour_id = t2.tour_id