oracle中的Sum case语句SQL Group By Case description remove nulls

Sum case statement in oracle SQL Group By Case description remove nulls

帐号 DR_DESCRIPTION CR_DESCRIPTION DR_AMOUNT CR_AMOUNT
xxx-111-xxx 土地 60
xxx-111-xxx 现金 21300
xxx-111-xxx 首都 1789
xxx-111-xxx 柴油 480
xxx-111-xxx 气体 19687
xxx-111-xxx 食物 1193
xxx-111-xxx 1789
xxx-111-xxx 0

我有以下查询结果集

但是,我想做的是删除空值并使结果如下所示:

帐号 DR_DESCRIPTION CR_DESCRIPTION DR_AMOUNT CR_AMOUNT
xxx-111-xxx 土地 柴油 60 480
xxx-111-xxx 现金 气体 21300 19687
xxx-111-xxx 首都 食物 1789 1193
xxx-111-xxx 1789
xxx-111-xxx 0

我使用的查询是:

SELECT account,
    CASE WHEN debit_credit  = 'DR' THEN DESCRIPTION END dr_description,
    CASE WHEN debit_credit  = 'CR' THEN DESCRIPTION END cr_description,
    SUM(CASE WHEN debit_credit = 'DR' THEN income_amount END) DR_AMOUNT,
    SUM(CASE WHEN debit_credit = 'CR' THEN income_amount END) CR_amount
FROM xxxxx
GROUP BY account, CASE WHEN debit_credit = 'DR' THEN DESCRIPTION END, 
    CASE WHEN debit_credit  = 'CR' THEN DESCRIPTION END

我认为您只需要修正您当前的查询:

select account,
       max(case when debit_credit = 'DR' then DESCRIPTION end) as dr_description,
       max(case when debit_credit = 'CR' then DESCRIPTION end) as cr_description,
       sum(case when debit_credit = 'DR' then income_amount end) as DR_AMOUNT,                                                 
       sum(case when debit_credit = 'CR' then income_amount end) as CR_amount
from  xxxxx
group by account;

以上 returns 每个帐户一行。如果您想要单独的借记和贷记,那么您可以使用 row_number()。假设您有一列指定顺序:

select account,
       max(case when debit_credit = 'DR' then DESCRIPTION end) as dr_description,
       max(case when debit_credit = 'CR' then DESCRIPTION end) as cr_description,
       sum(case when debit_credit = 'DR' then income_amount end) as DR_AMOUNT,                                                 
       sum(case when debit_credit = 'CR' then income_amount end) as CR_amount
from (select x.*,
             row_number() over (partition by account, debit_credit order by <ordering column>) as seqnum
      from xxxxx x
     ) x
group by account, seqnum;