减去两个值时返回空值

Returning null values when subtracting two values

我是 运行 一个查询,用于获取特定客户在两个时间段(7 月和 8 月)的总数。然后将两者相减得到差值。但是,即使此客户的 7 月和 8 月都存在值,我在减法时得到空值。

select 语句的这一部分是 returning 空值,即使我知道 values/numbers 存在。 'AUG.amount - JUL.amount as Final_Result'

我已经 运行 分别尝试了 7 月和 8 月的表格,他们 return sum/total 为 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 的八月和七月之间的差异

您可以通过以下方式直接获取: 编辑查询以按月使用 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 日。

干杯!!

您可以使用 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'