用连接表分组并计算总和

时间:2017-03-02 16:58:47

标签: mysql join group-by

我有table1这样:

ID uid jid type val
1   1   1   1   1
2   1   1   1   10
3   1   2   1   100
4   1   3   1   1000
5   1   4   2   2

加入table2

ID uid jid stat time
1   1   1   1   100
2   1   1   1   200
3   1   1   4   300
4   1   2   2   400

我尝试从table1获取val的SUM,通过uid对其进行分组,并通过此查询键入并连接table2:

SELECT a.uid, a.type, SUM(a.val) as t1, SUM(a.val)*COUNT(distinct(a.id))/COUNT(a.id) as t2, MAX(b.time) as max_time
FROM table1 as a
LEFT JOIN table2 as b on b.uid = a.uid and b.jid = a.jid and b.stat = 1
GROUP BY a.uid, a.type

结果我得到了这个值:

uid type t1     t2     max_time
1   1   1122  748.0000  200
1   2      2    2.0000  NULL

但类型= 1的总数应为:1111(不是1122而不是748)

请告诉我我做错了什么。

2 个答案:

答案 0 :(得分:0)

您需要在select语句中使用带有a.uid的DISTINCT。更正的查询如下:

SELECT DISTINCT(a.uid),a.type,SUM(a.val)AS t1,SUM(a.val)* COUNT(DISTINCT(a.id))/ COUNT(a.id)AS t2, MAX(b.time)AS max_time FROM table1 AS a LEFT JOIN table2 AS b ON b.uid = a.uid AND b.jid = a.jid AND b.stat = 1 GROUP BY a.uid,a.type

答案 1 :(得分:0)

你可以重新检查sql:

SELECT auid,atype,SUM(aval) ,SUM(aval)* COUNT(DISTINCT(援助))/ COUNT(援助)AS t2,MAX(btime)AS max_time 从 ( SELECT DISTINCT(a.uid)AS auid,a.type AS atype,a.val AS aval,a.id AS aid,b.time AS btime FROM table1 AS a LEFT JOIN table2 AS b ON b.uid = a.uid AND b.jid = a.jid AND b.stat = 1 )AS grouptable GROUP BY auid,atype

我得到的输出:

auid atype sum(aval)t2 max_time

1 1 1111 1111.0000 200

1 2 2 2.0000(NULL)


您正在寻找的结果是什么?