我有两张桌子即。订单和订购。订单表包含日期,订单表包含该订单的数量和价格。我想找到价格变化的日期。例如今天价格为10,2天后变为11,然后在接下来的5天内保持11,然后在5天后再变为10,所以结果将是3个日期10,11,10,日期将是当价格改变
Date price
'2015-04-29 14:48:23', 15.99
'2015-04-30 14:20:11', 15.99
'2015-04-30 21:05:11', 15.99
'2015-05-04 01:41:12', 15.99
'2015-07-28 05:52:20', 15.99
'2015-07-29 16:55:48', 15.99
'2015-08-01 00:31:53', 15.99
'2015-08-15 22:41:49', 15.99
'2015-08-17 02:37:43', 15.99
'2015-08-17 13:28:03', 15.99
'2015-08-23 04:16:31', 15.99
'2015-08-27 08:43:48', 15.99
'2015-08-28 18:42:27', 15.99
'2015-08-29 15:47:17', 15.99
'2015-08-30 03:33:15', 15.99
'2015-10-29 03:45:25', 15.99
'2015-10-29 18:24:20', 15.99
'2015-10-30 18:17:18', 15.99
'2015-11-02 15:28:16', 16.99
'2015-11-03 01:59:03', 16.99
'2015-11-14 18:22:39', 16.99
'2015-11-20 02:48:59', 16.99
'2015-12-16 18:59:54', 16.99
'2015-12-28 04:08:22', 16.99
'2016-01-12 03:21:35', 16.99
'2016-01-18 00:43:56', 16.99
'2016-01-18 20:11:23', 16.99
'2016-02-10 19:07:57', 16.99
'2016-02-26 14:24:29', 16.99
'2016-03-28 10:17:24', 16.99
'2016-03-31 23:33:53', 16.99
'2016-04-01 20:03:03', 17.99
'2016-05-31 20:30:50', 15.99
我希望获得价格变动的所有日期。这里输出将是
'2015-04-29 14:48:23', 15.99
'2015-11-02 15:28:16', 16.99
'2016-04-01 20:03:03', 17.99
'2016-05-31 20:30:50', 15.99
即。显示价格变更的日期。
到目前为止,我已编写此MYSQL查询,但它提供了所有行,但未过滤结果:
SELECT date, price FROM orderitem
inner join orders o1 on o1.orderid = orderitem.orderid
where productname = 'IBC'
and price <> (
select price from orderitem
inner join orders on orders.orderid = orderitem.orderid
where orders.date< o1.date
order by date desc
limit 1
)
任何建议都将不胜感激。
答案 0 :(得分:1)
对于这样的事情,你需要两次通过,因为你将每行与前一行进行比较。
这样做的一种方法是首先:
SET @lastprice = 0.0;
然后,你的第一次通过&#34;看起来像是:
SELECT `Date`, @lastprice AS `oldprice`, @lastprice := `price` AS `newprice`
FROM `tablename` ORDER BY `Date` ASC;
此处的顺序非常重要,因为您希望按时间顺序构建时间轴。
然后,您需要做的就是从旧结果和新价格不同的结果中检索行。这样的事情会做:
SELECT * FROM ("Above subquery here") `tmp` WHERE `oldprice` != `newprice`;
您的最终查询将如下所示:
SET @lastprice = 0.0;
SELECT * FROM (
SELECT `Date`, @lastprice AS `oldprice`, @lastprice := `price` AS `newprice`
FORM `tablename` ORDER BY `Date` ASC
) `tmp`
WHERE `oldprice` != `newprice`;
或者,您可能更喜欢使用临时表来存储子查询结果。在这种情况下,它看起来像这样:
SET @lastprice = 0.0;
CREATE TEMPORARY TABLE `tmp`
SELECT `Date`, @lastprice AS `oldprice`, @lastprice := `price` AS `newprice`
FROM `tablename` ORDER BY `Date` ASC;
SELECT * FROM `tmp` WHERE `oldprice` != `newprice`;
DROP TEMPORARY TABLE `tmp`;
确切的实施取决于您,但这是一个很好的方法。