MySQL多个sum表

时间:2014-07-23 02:12:07

标签: mysql

来自以下小提琴http://sqlfiddle.com/#!2/8f1d2/5我想将交叉表作为下面的查询求和,但是我遇到了重复的sale_event值的问题。你对它有什么想法。

SELECT
 a.province_id,
 SUM(a.sale_event) AS sale_eventTotal,
 SUM(d.order_fullpay) AS order_fullpayTotal
FROM
    san_activites a
LEFT JOIN
    sale_event_detail d
ON
    a.san_activity_id = d.san_activity_id
WHERE 
    a.entry_date BETWEEN '2014-7-1' AND '2014-7-30'
GROUP BY a.province_id

3 个答案:

答案 0 :(得分:0)

只需删除GROUP BY a.province_id并运行它为我工作的查询。

答案 1 :(得分:0)

san_activity_id上的add a unique index或查询时的重复数据删除:

SELECT 
 SUM(a.sale_event) AS sale_eventTotal,
 SUM(d.order_fullpay) AS order_fullpayTotal
FROM
    san_activites a
LEFT JOIN
    (select * from sale_event_detail group by san_activity_id) d
ON
    a.san_activity_id = d.san_activity_id
WHERE 
    a.entry_date BETWEEN '2014-7-1' AND '2014-7-30'
GROUP BY a.province_id

fiddle

答案 2 :(得分:0)

我能够得到我认为你想要的结果。结果带回了3 | 10
4 | 20

SELECT 
 SUM(a.sale_event) AS sale_eventTotal,
 SUM(d.order_fullpayTotal) AS order_fullpayTotal
FROM
    san_activites a
LEFT JOIN
    (select SUM(order_fullpay) AS order_fullpayTotal, san_activity_id from sale_event_detail group by san_activity_id) d
ON
    a.san_activity_id = d.san_activity_id
WHERE 
    a.entry_date BETWEEN '2014-7-1' AND '2014-7-30'
GROUP BY a.province_id

Fiddle