Two where condition for same column using group by

前端 未结 2 893
轻奢々
轻奢々 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: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

提交回复
热议问题