我有一张看起来像这样的桌子
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列上使用算术运算并检查哪个折扣价与其匹配并返回相应的折扣数量。
假设Master_Price为100且输入Master_Price - 20则应返回值12(存在于第二行)或整行。如果Master_Price为200并且我输入Master_Price - 50则应返回值7(存在于第三行)或整个行,依此类推。如果Master_Price是500并且我输入Master_Price - 100那么它应该返回30或整行而不是具有NULL的行
输入要从Master_Price中减去的整数的选项应该在查询中。即使它是硬编码也没关系
请参阅上面的评论,但我认为此查询应该有效:
(如果没有找到任何行,它就不会得到整行。)
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