首页 > 解决方案 > 如果 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 语句,但我陷入了逻辑中。

标签: sqlpostgresql

解决方案


因此,您希望 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)

推荐阅读