简体   繁体   中英

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

account DR_DESCRIPTION CR_DESCRIPTION DR_AMOUNT CR_AMOUNT
xxx-111-xxx land 60
xxx-111-xxx cash 21300
xxx-111-xxx capital 1789
xxx-111-xxx diesel 480
xxx-111-xxx gas 19687
xxx-111-xxx food 1193
xxx-111-xxx water 1789
xxx-111-xxx electricity 0

I have the following result set of a query

However, what I would like to do is remove the nulls and make the results look like this:

account DR_DESCRIPTION CR_DESCRIPTION DR_AMOUNT CR_AMOUNT
xxx-111-xxx land diesel 60 480
xxx-111-xxx cash gas 21300 19687
xxx-111-xxx capital food 1789 1193
xxx-111-xxx water 1789
xxx-111-xxx electricity 0

The query I am using is:

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

I think you just need to fix your current query:

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;

The above returns one row per account. If you want each debit and credit individually, then you would use row_number() . Assuming you have a column that specifies the ordering:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM