sql - 如果 subquery2 中不存在该记录,如何将记录从 subquery1 拉到 subquery2
问题描述
我对定价数据的第 1 周和第 2 周都有一个子查询,其中包含 sku、商店编号、正常价格和有效价格,如下所示:
子查询1 =
week sku store_num regular_price effective_price
1 123 5456 1.99 1.99
1 456 5423 2.99 .99
1 789 6788 1.49 1.49
1 222 6577 1.79 1.49
子查询2 =
week sku store_num regular_price effective_price
2 123 5456 0.00 1.99
2 456 5423 1.79 .95
2 789 6788 0.00 0.00
2 888 3446 1.00 1.00
我想要做的是将在子查询 1 中找到但在子查询 2 (0.00) 中未找到的常规有效价格前移。所以我希望我的输出看起来像这样:
输出 =
week sku store_num regular_price effective_price
2 123 5456 1.99 1.99
2 456 5423 1.79 .95
2 789 6788 1.49 1.49
2 888 3446 1.00 1.00
我该怎么做呢?我尝试过使用 case 语句,但我陷入了逻辑中。
解决方案
因此,您希望 subquery2 中的值不为 0,否则它们将替换为 subquery1 中的值。NULL
如果您使用而不是0
表示缺失值,这会更简单一些。
select week, sku, store_num,
coalesce(nullif(s2.regular_price, 0), s1.regular_price) as regular_price,
coalesce(nullif(s2.effective_price, 0), s1.effective_price) as effective_price
from (<subquery2>) s2 left join
(<subquery1>) s1
using (week, sku, store_num)
推荐阅读
- makefile - Make:目标选择
- c# - 变量类型列表
在对象中,我怎样才能制作这个对象的列表 - r - 处理带有多个 csv 列表的两行标题
- mysql - MacOS Mojave - brew install mysql@5.7 - 用户'root'@'localhost'的访问被拒绝
- python - 如何检查一个数组是否在 Python 的数组列表中?
- node.js - module.exports 导出默认值:如何以正确的方式重写?
- python - 优先考虑来自 csv 的重复项
- linux - 两个默认网关上的路由问题
- reporting-services - 从 Reporting Services 迁移到 SSDT
- kubernetes - Kubernetes 不创建证书