首页 > 解决方案 > 返回不同列中具有特定值的所有行

问题描述

我有一张看起来像这样的桌子

Time            Master_Price    Discounted_price1   Discounted_qty1 Discounted_price2   Discounted_qty2 Discounted_price3   Discounted_qty3
1552279758      100                     90                  5               80                  10              70              15
1552279759      200                     195                 6               185                 7               80              12
1552279760      300                     285                 11              200                 9               150             7
1552279761      400                     300                 20              250                 25              220             30
1552279763      500                     400                 30              350                 5               300             8
1552279766      500                     400                 NULL            350                 9               300             9

Time 列是唯一的,采用 unix 格式。

要求是对 Master_Price 列进行算术运算,并检查哪个 Discounted Price 与之匹配并返回相应的 Discounted Qty。

假设如果 Master_Price 是 100 并且我输入 Master_Price - 20,那么应该返回值 12(存在于第二行)或整行。如果 Master_Price 为 200 并且我输入 Master_Price - 50,则应返回值 7(存在于第三行)或整行,依此类推。如果 Master_Price 是 500 并且我输入 Master_Price - 100 那么它应该返回 30 或整行而不是具有 NULL 的行

输入要从 Master_Price 中减去的整数的选项应该在查询中。即使是硬编码也没关系

标签: mysqlsqlgroup-bywherehaving

解决方案


请参阅上面的评论,但我认为此查询应该有效:

(如果没有找到,它不会得到整行。)

select @MP := 500;
select @DISCOUNT := 100;
select 
CASE
    WHEN Discounted_price1 = Master_Price - @DISCOUNT THEN Discounted_qty1 
    WHEN Discounted_price2 = Master_Price - @DISCOUNT THEN Discounted_qty2 
    WHEN Discounted_price3 = Master_Price - @DISCOUNT THEN Discounted_qty3 
ELSE 'None'
END as qty
from prices where Master_Price = @MP and ((Discounted_price1 = Master_Price - @DISCOUNT and Discounted_qty1 >=0) or (Discounted_price2 = Master_Price - @DISCOUNT and Discounted_qty2 >=0) or (Discounted_price3 = Master_Price - @DISCOUNT  and Discounted_qty3 >=0));

我做了一个小提琴来演示/玩它。 http://sqlfiddle.com/#!9/0166cc/16


推荐阅读