Oracle SQL请求

tjvv9vkg  于 2023-06-22  发布在  Oracle
关注(0)|答案(1)|浏览(122)

下面是两个SQL请求

select sum(amount) as personAmountPayments, personId from payments where code = '023' and paiementDate= '01/04/2023' group by payments.personId

select sum(amount) as personAmountExtraPayments, personId from extraPayments where code = '23' and paiementDate = '01/04/2023' group by extraPayments.personId

这两份申请给予了2023年4月每人的付款总额和代码23。
有些人可以在第一个表,而有些人在第二个表。但有些人可以在两个表。
我想列举如下:
如果某人仅在一个表中:personAmountPayments或personAmountExtraPayments
但如果它们都在两个表中:personAmountPayments - personAmountExtraPayments
当然,我也想添加personId列。
你能帮我处理一下SQL请求吗?

hujrc8aj

hujrc8aj1#

您可以使用查询并执行FULL OUTER JOIN来连接它们,当两者都是可选的时:

SELECT COALESCE(p.personId, ep.personId) AS personId,
       p.personAmountPayments,
       ep.personAmountExtraPayments
FROM   (
         select personId,
                sum(amount) as personAmountPayments
         from   payments
         where  code         = '023'
         and    paiementDate = DATE '2023-04-01'
         group by personId
       ) p
       FULL OUTER JOIN
       (
         select personId,
                sum(amount) as personAmountExtraPayments
         from   extraPayments
         where  code         = '23'
         and    paiementDate = DATE '2023-04-01'
         group by personId
       ) ep
       ON p.personId = ep.personId;

相关问题