使用group by得到值的总和

时间:2018-01-05 11:36:52

标签: mysql

我有一张桌子t2。我需要将vqtyfrom_brto_br的总和作为两列。我的表格如下。 我的数据库架构位于sqlfiddle

T1:

id    branch_name
-------------------
1     branch1
2     branch2
3     branch3
4     branch4
5     branch5
6     branch6

T2:

id    from_br    to_br     qty
--------------------------------
1     1         3          10
2     2         4          20
3     3         2          30
4     2         3          40
5     1         4          50 
6     4         5          60 

期待结果:

branch_name    send        received
-------------------------------
branch1        60          0          
branch2        60          30
branch3        30          50
branch4        60          70
branch5        0           60 

我试过的查询是:

SELECT t1.branch_name, 
   COALESCE(SUM(send.vqty), 0) AS send, 
   COALESCE(SUM(receive.vqty), 0) AS received 
FROM t1  
LEFT JOIN t2 AS send on t1.id = send.from_br  
LEFT JOIN t2 AS receive on t1.id = receive.to_br 
GROUP BY t1.branch_name, send.from_br, receive.from_br

1 个答案:

答案 0 :(得分:0)

我感谢下面的帮助

 SELECT t.branch_name,  COALESCE(SUM(t.send), 0) AS send, 
    COALESCE(SUM(received), 0) AS received  from  (SELECT t1.branch_name, 
           COALESCE(SUM(send.vqty), 0) AS send, 
           COALESCE(SUM(receive.vqty), 0) AS received 
        FROM t1  
        LEFT JOIN t2 AS send on t1.id = send.from_br  
        LEFT JOIN t2 AS receive on t1.id = receive.to_br 
        GROUP BY t1.branch_name, send.from_br, receive.from_br) as t 
        GROUP BY t.branch_name

检查http://sqlfiddle.com/#!9/af0973/7

相关问题