Two where condition for same column using group by

前端 未结 2 845
轻奢々
轻奢々 2021-01-28 03:55

I am having two tables, t1, t2. My tables and expected result are given below. My table schema is in sqlfiddle

t1:

id    branch_name
1     branch1
2              


        
相关标签:
2条回答
  • 2021-01-28 04:33

    I think this is the query you are looking for:

    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

    0 讨论(0)
  • 2021-01-28 04:43

    E.g.

    SELECT x.*
         , COALESCE(sent,0) sent
         , COALESCE(received,0) received
      FROM t1 x
      LEFT 
      JOIN 
         ( SELECT from_br
                , SUM(vqty) sent
             FROM t2
            GROUP
               BY from_br
         ) a
        ON a.from_br = x.id
      LEFT
      JOIN
         ( SELECT to_br
                , SUM(vqty) received
             FROM t2
            GROUP
               BY to_br
         ) b
        ON b.to_br = x.id
     ORDER
        BY id;
    

    http://sqlfiddle.com/#!9/af0973/21

    0 讨论(0)
提交回复
热议问题