【问题标题】:Return All Rows With Particular Value In Different Columns返回不同列中具有特定值的所有行
【发布时间】:2019-03-12 13:28:46
【问题描述】:

我有一张像这样的桌子

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

时间列是唯一的,采用 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 中减去的整数的选项。就算是硬编码也没关系

【问题讨论】:

  • 我想我几乎已经为你解决了这个问题,但我很困惑。根据您的解释(或我对它的理解),如果 Master_Price 是 100,并且您想要 Master_Price - 20,它应该返回 10,而不是 12。第 2 行的主价格为 200,所以如果它的 100 和 80(100 -20),然后它会在第 1 行找到 discount2,并返回 discount_qty_2。如果我误解了你的逻辑,请告诉我。

标签: mysql sql group-by where having


【解决方案1】:

见我上面的评论,但我认为这个查询应该有效:

(如果没有找到,则不会获取整行。)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多