减去两个值时返回空值

时间:2019-10-17 18:18:21

标签: sql oracle aggregation

我正在运行一个查询,以获取两个时段(7月和8月)中特定客户的总数。然后将两者相减得出差值。但是,即使该客户端的Jul和Aug值都存在,我在减去时也会得到空值。

即使我知道值/数字存在,select语句的这一部分仍将返回空值。 “ AUG.amount-JUL.amount作为Final_Result”

我尝试分别运行Jul和Aug表,它们确实返回了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

预期结果应显示AH的8月和7月之间的差异

2 个答案:

答案 0 :(得分:2)

您可以使用以下方法直接获取它: 编辑查询以按月使用trunc。

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;

此外,您忘记在查询中包括2019年8月31日。

干杯!

答案 1 :(得分:2)

您可以使用Conditional Aggregation而不使用group by表达式,因为您只有一个参与方名称:

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'