简体   繁体   English

从两个表中选择并有条件地折叠一列

[英]select from two tables and conditionally collapse one column

I have a list of Products 我有Products清单

upc | name     | price | qty
----------------------------
1   | apple    |  1.00 |  3
2   | peach    |  2.00 |  7
3   | melon    |  1.75 |  2

and SaleProducts SaleProducts

upc | price
------------
2   | 1.90

I want to select from Products but also sale price from SaleProducts (if product is on sale). 我要从“产品”中选择,还要从“ SaleProducts”中选择销售价格(如果产品正在销售)。 This is what I came up with: 这是我想出的:

SELECT t1.upc, t1.name, MIN(t1.price) AS 'price', t1.qty
FROM (
  SELECT p.upc, p.name, p.price, p.qty
  FROM products p
    UNION
  SELECT sp.upc, NULL, sp.price, NULL
  FROM saleproducts sp
  ) t1
GROUP BY t1.upc;

Output: 输出:

upc | name     | price | qty
----------------------------
1   | apple    |  1.00 |  3
2   | peach    |  1.90 |  7
3   | melon    |  1.75 |  2

Can anyone suggest a more elegant way to accomplish this? 谁能建议一种更优雅的方式来实现这一目标? Im aware of similar question but my goal is to grab whichever price is lower, so COALESCE wouldn't work. 我知道类似的问题,但我的目标是抢下任何一个较低的价格,所以COALESCE不起作用。

The only restriction is, I must use vanilla SQL, no stored procs or IF's. 唯一的限制是,我必须使用原始SQL,没有存储的proc或IF。

Try this instead using CASE : 尝试使用CASE代替:

SELECT p.upc, p.name,
  CASE WHEN sp.price IS NOT NULL
    THEN CASE WHEN p.price > sp.price
      THEN sp.price
      ELSE p.price
    END
    ELSE p.price
  END price, p.qty
FROM products p LEFT JOIN saleproducts sp ON p.upc = sp.upc;

It will prefer to use the price from saleproducts when it's available. 它会倾向于使用从价格saleproducts当它可用。 If there is not a sale price for that product it will instead use the price from products . 如果没有该产品的销售价格,它将使用products的价格。

EDIT - I've updated my answer so that it always gets the lowest price. 编辑 -我已经更新了答案,以便始终获得最低价格。 FWIW I can't imagine why you'd bother having a sale price which is actually higher than your list price. FWIW,我无法想象为什么您会烦恼实际上要高于标价的销售价格。

This seems more like the job for a left outer join : 这似乎更像是left outer join

SELECT p.upc, p.name,
       (case when sp.price is null or p.price < sp.upc  then p.price
             else sp.price
        end) as price,
       p.qty
FROM products p left outer join
     salesproducts sp
     on p.upc = sp.upc;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM