根据完整的外部联接结果从两列添加数据

时间:2019-07-16 06:45:19

标签: sql teradata outer-join

我从完全外部联接中获得的数据如下所示。我正在尝试建立一个SQL查询来执行以下操作。

  1. ha和da是相同的值,但任何一个都可以是None
  2. 执行hc + dc(不使用hc或dc时将其视为0)

我的数据如下。

My data from full outer join looks like this

我期望这样的结果

enter image description here

我正在尝试查询:

select 
(case when h.ha not in ('None') then h.ha else h.da end) as acc,
(case when h.hc not in ('None') then cast(h.hc as integer) else 0 end 
 + 
case when h.dc not in ('None') then cast(h.dc as integer) else 0 end) as tc 
from 

(select h.acc as ha, hc, d.acc as da, dc from h_data h
full outer join
d_data d
on h.acc = d.acc
) h

我得到A character string failed conversion to a numeric value不确定我在哪里犯错。

1 个答案:

答案 0 :(得分:1)

尽管您的示例对我来说您的想法是正确的,但我不使用Teradata,您只将null错误对待。我猜None只是数据库浏览器中null的某种呈现。标准coalesce函数IMHO可以完成这项工作:

with h_data as (
  select 'AA' as acc, 1 as hc union
  select 'BB' as acc, 1 as hc union
  select 'EE' as acc, 1 as hc union
  select 'FF' as acc, 2 as hc union
  select 'GG' as acc, 1 as hc union
  select 'HH' as acc, 1 as hc
), d_data as (
  select 'CC' as acc, 1 as dc union
  select 'DD' as acc, 1 as dc union
  select 'EE' as acc, 2 as dc union
  select 'GG' as acc, 4 as dc
)
select coalesce(h.acc, d.acc) as acc,
  coalesce(h.hc, 0) + coalesce(d.dc, 0) as tc
from h_data h
full outer join d_data d on h.acc = d.acc
order by 1

Tested on PG.