完全外部联接与group by query

时间:2014-12-28 21:24:12

标签: sql oracle

按月计算公司利润,计算公司利润如下: sum of incoming minus outgoing

表:

  1. 传入(金额,月份)
  2. 传出(金额,月份)
  3. 数据类型:

    • 月整数,范围1-12
    • 金额整数

    我试过

    SELECT month,tsum-bsum FROM
    (SELECT month,SUM(amount) tsum FROM incoming GROUP BY month
    FULL OUTER JOIN
        (SELECT month,SUM(amount) bsum FROM outgoing GROUP BY month)
    )
    ON incoming.month=outgoing.month;
    

    但是加入后月份可以为空,这会导致tsum-bsum出现问题。

2 个答案:

答案 0 :(得分:0)

这里是示例查询

SELECT COALESCE(in.month, out.month) as month, sum(COALESCE(in.amount,0) - COALESCE(out.amount,0)) as profit
FROM
    incoming as in
FULL OUTER JOIN
    outgoing as out
ON in.month = out.month;
GROUP BY COALESCE(in.month, out.month)

答案 1 :(得分:0)

使用coalesce()

SELECT coalesce(i.month, o.month) as month, i.tsum - o.bsum
FROM (SELECT month, SUM(amount) as tsum FROM incoming GROUP BY month) i
     FULL OUTER JOIN
     (SELECT month, SUM(amount) as bsum FROM outgoing GROUP BY month) o
     ON i.month = o.month;

请注意,如果值为NULL,差异可能为NULL,因此您可能需要:

SELECT coalesce(i.month, o.month) as month,
       coalesce(i.tsum, 0) - coalesce(o.bsum, 0) as diff
FROM (SELECT month, SUM(amount) as tsum FROM incoming GROUP BY month) i
     FULL OUTER JOIN
     (SELECT month, SUM(amount) as bsum FROM outgoing GROUP BY month) o
     ON i.month = o.month;