【问题标题】:Why isn't Teradata EXCEPT returning expected results?为什么 Teradata EXCEPT 不返回预期结果?
【发布时间】:2021-03-16 21:42:59
【问题描述】:

为什么 EXCEPT 没有返回预期结果?我觉得这应该可行,但它返回零行。但是,如果我计算 T3 中不在 t2 中的 order-buid-tie 行,我会得到数千个结果,反之亦然。

人工审核

--first table (T3) without T2 match --178k
select count(*) --178K
from LAB3.Report_stg st3
left join LAB2.Report_stg  st2 
on st3.order_num = st2.order_num and st3.buid= st2.buid and st3.tie_nbr = st2.tie_num
where st2.tie_num is null

--second table (t2) without match in first (T3)
select count(*) --12.5M
from LAB2.Report_stg st2
left join LAB3.Report_stg st3
on st3.order_num = st2.order_num and st3.buid = st2.buid and st3.tie_num = st2.tie_num
where st3.tie_num is null

让我们试试 EXCEPT。我希望这里有 178k 行并得到零

--to avoid cartesian join
--select all mismatched tie_nums
--unless (EXCEPT if) that tie_num exists as a matched set between the two tables
select t3.order_num, t3.buid, t3.tie_num as t3_tie
from LAB3.Report_stg t3
left join LAB2.Report_stg t2
on t3.order_num = t2.order_num and t3.buid = t2.buid and t3.tie_num <> t2.tie_num
except
  (select st3.order_num, st3.buid, st3.tie_num 
  from LAB3.Report_stg st3
  left join LAB2.Report_stg st2
  on st3.order_num = st2.order_num and st3.buid = st2.buid and st3.tie_num = st2.tie_num
  )

【问题讨论】:

  • EXCEPT无关。您将谓词从 ON ... st3.tie_nbr = st2.tie_num WHERE st2.Tie_num is null(反连接)更改为 ON ... t3.tie_num &lt;&gt; t2.tie_num,这实际上使 EXCEPT 之前的部分变为内连接。
  • 谢谢!我想到了。第二个子句必须是 INNER JOIN!

标签: sql join teradata diff except


【解决方案1】:

啊,我想通了!因此,子句的第二部分(在 EXCEPT SELECT 内)需要是一个 INNER JOIN 才能达到预期的效果。同样,我试图拉出的是 T3 中相同 T2 订单上的所有平局,但表之间没有匹配。

--to avoid cartesian join
--select all mismatched tie_nums
--unless (EXCEPT if) that tie_num exists as a matched set between the two tables
select t3.order_num, t3.buid, t3.tie_num as t3_tie
from LAB3.Report_stg t3
left join LAB2.Report_stg t2
on t3.order_num = t2.order_num and t3.buid = t2.buid and t3.tie_num <> t2.tie_num
except
  (select st3.order_num, st3.buid, st3.tie_num 
  from LAB3.Report_stg st3
  INNER join LAB2.Report_stg st2
  on st3.order_num = st2.order_num and st3.buid = st2.buid and st3.tie_num = st2.tie_num
  )

示例: T3 |订单号 |领带号码 | | -------- | -------------- | | 123 | 1 | | 123 | 2 | | 123 | 3 | |第456章1| |第456章4|

T2 |订单号 |领带号码 | | -------- | -------------- | | 123 | 2 | | 123 | 4 | | 123 | 5 | |第456章1| |第456章3|

使用上述查询的结果

T3 |订单号 |领带号码 | | -------- | -------------- | | 123 | 1 | | 123 | 3 | |第456章4|

因此,理想情况下,我会将其与逆向联合,以将 T2 中不在 t3 中的订单关系放入同一结果集中。但这意味着我刚刚写了一个手册 FULL OUTER JOIN SMH

【讨论】:

    猜你喜欢
    • 2011-01-29
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2023-02-07
    相关资源
    最近更新 更多