0

我有以下两个表格:

 content:
 ========
 cid | iid | qty
 ---------------
   1 |   7 | 42
   2 |   7 |  1
   3 |   8 | 21

 ret:
 ====
 rid | cid | qty
 --------------
   1 |   1 |   2
   2 |   1 |  10
   3 |   2 |   1

我想检索每个 iid 的总和例如content.qtyret.qty 对于给定的表,结果将是:

iid=7, SUM(content.qty) = 43, SUM(ret.qty)=13

iid=8, SUM(content.qty) = 21, SUM(ret.qty)=0

有没有办法在一个查询中做到这一点?

先谢谢了!

4

1 回答 1

0

这有点复杂,因为您不希望总和中有重复项。要解决该问题,请将聚合单独作为子查询进行。第一个直接在content第二个连接上返回contentfromret以获取该iid列。

以下查询遵循此方法,并假定它cid是 上的唯一键content

select c.iid, c.qty + coalesce(r.qty, 0)
from (select c.iid, SUM(qty) as cqty
      from content c 
      group by c.iid
     ) c left outer join
     (select c.iid, SUM(r.qty) as rqty
      from ret r join
           content c
           on r.cid = c.cid
      group by c.iid
     ) r
     on c.iid = r.iid;
于 2013-05-29T16:16:13.193 回答