首页 > 解决方案 > 返回不同的行,同时从不同的列中排除一列

问题描述

我有以下查询...

SELECT           
      DEP.CUST_ORG_CD,
      DEP.CUST_NO,
      DEP.DP_ACT_NO
FROM R_DBLNK_US.DW_TRN_DEPO_ACC_D DEP

UNION

SELECT
      DEP.CUST_ORG_CD,
      DEP.CUST_NO,
      DEP.DP_ACT_NO
FROM R_DBLNK_US.DW_MST_ACC_D DEP

...返回两行(每个表各一行)

CUST_ORG_CD    CUST_NO    ACT_NO
5              321        8
5              321        9

我存储在一个临时表中。然后我想返回所有三列,但在前两列上使用 DISTINCT,这样在这种情况下不会返回第二行。

标签: sqlsql-servertsqlsubqueryunion

解决方案


我建议not exists在第二个子查询中过滤掉与前两列的第一个结果集匹配的记录。

select cust_org_cd, cust_no,dp_act_no
from r_dblnk_us.dw_trn_depo_acc_d
union all
select cust_org_cd, cust_no, dp_act_no
from r_dblnk_us.dw_mst_acc_d d2
where not exists (
    select 1
    from r_dblnk_us.dw_trn_depo_acc_d d1
    where d1.cust_org_cd = d2.cust_org_cd and d1.cust_no = d2.cust_no
)

旁注:我union改为union all; 除非子查询本身产生重复,否则这不会改变结果集,而且效率更高。


推荐阅读