两个使用group by的相同列的条件

时间:2018-01-05 08:57:59

标签: mysql

我有两张桌子,t1,t2。我的表格和预期结果如下。 我的表架构位于sqlfiddle

T1:

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

T2:

id    VBRNCH    VTOBRN    vqty
1     1         0         10
2     2         0         20
3     3         0         30
4     0         4         40
5     0         5         50

预期结果是:

branch_name    send    received
1               10     0
2               20     0
3               30     0
4               0      40
5               0      50

我所尝试的是:

SELECT
  b1.branch_name,
  i1.vqty AS send,
  i2.vqty AS received
FROM t2 i1
INNER
JOIN t1 b1
  ON b1.id = i1.VBRNCH
INNER JOIN t2 i2
  ON b1.id = i2.VTOBRN
GROUP
BY i1.VTOBRN,
   i2.VBRNCH;

但我得零行。

2 个答案:

答案 0 :(得分:1)

我认为这是您正在寻找的查询:

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.VBRNCH  
LEFT JOIN t2 AS receive on t1.id = receive.VTOBRN 
GROUP BY t1.branch_name

Demo here

答案 1 :(得分:0)