sql - 返回不同的行,同时从不同的列中排除一列
问题描述
我有以下查询...
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,这样在这种情况下不会返回第二行。
解决方案
我建议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
; 除非子查询本身产生重复,否则这不会改变结果集,而且效率更高。
推荐阅读
- flutter - Flutter 依赖项,iOS 问题(未找到 Flutter.h 文件)
- sql - 试图编写最流行产品的查询(意思是具有最不同客户的产品)超级卡住。不使用视图
- apache - 无法使用 SSL 登录 GeoServer 2.19
- amazon-web-services - AWS EC2 成本比较在一处?
- node.js - npm 错误!代码 ENOTEMPTY npm 错误!在 Nextjs 项目中安装任何 npm 依赖项时的系统调用重命名
- python - 如何根据匹配使用熊猫样式为 excel 单元格着色?
- debugging - 在 WebStorm 中调试安全帽可靠性测试
- youtube - youtube VTT 字幕中的空行
- javascript - 为什么我的随机数会出现 Uncaught TypeError?
- python - Django 错误:NoReverseMatch at / ;查看错误的 urlpattern?