简体   繁体   中英

Returning null values when subtracting two values

I am running a query to get the total for a particular client over two time periods (jul and aug). Then subtracting the two to get the difference. However, I get null values when I am subtracting even though values exist for both Jul and Aug for this client.

This part of the select statement is returning null value even though I know the values/numbers exist. 'AUG.amount - JUL.amount as Final_Result'

I have tried running the Jul and Aug tables individually and they do return sum/total for AH.

SELECT AUG.party_name, AUG.amount - JUL.amount as Final_Result

FROM (select cl.party_name, sum(cl.amount)/1000 as amount
from CLIENT_PROFIT CL
where to_char(trade_date,'YYYYMMDD') between '20190801' and '20190830'
AND cl.party_name = 'AH'
group by cl.party_name
) AUG

LEFT JOIN

(select cl.party_name, sum(cl.amount)/1000 as amount
from CLIENT_PROFIT CL
where to_char(trade_date,'YYYYMMDD') between '20190701' and '20190731'
AND cl.party_name = 'AH'
group by cl.party_name) JUL

ON AUG.party_name = JUL.party_name

group by AUG.party_name

order by Final_Result DESC

the expected result should show the difference between Aug and Jul for AH

You can directly get it using following: Editing the query to use trunc by month.

select cl.party_name, 
(sum(case when trunc(trade_date,'month') = date '2019-08-01' then cl.amount end) 
- sum(case when trunc(trade_date,'month') = date '2019-07-01' then cl.amount end) )  /1000 as amount
from CLIENT_PROFIT CL
where trunc(trade_date) between date '2019-07-01' and date '2019-08-31'
AND cl.party_name = 'AH'
group by cl.party_name;

Also, You forgot to include 31st aug 2019 in your query.

Cheers!!

You can use Conditional Aggregation without group by expression since you have only one party name:

select 'AH' as party_name, 
       sum(case when to_char(trade_date,'YYYYMM')='201908' then cl.amount/1000 end) - 
       sum(case when to_char(trade_date,'YYYYMM')='201907' then cl.amount/1000 end)
       as Final_Result
  from CLIENT_PROFIT CL
 where cl.party_name = 'AH'

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