我有一个名为MySQL的简单表:
Table `share_prices`
+----------+-------+---------------------+
| stock_id | price | date |
+----------+-------+---------------------+
| 1 | 0.05 | 2010-02-24 01:00:00 |
| 2 | 3.25 | 2010-02-24 01:00:00 |
| 3 | 3.30 | 2010-02-24 01:00:00 |
| 1 | 0.50 | 2010-02-23 23:00:00 |
| 2 | 1.90 | 2010-02-23 23:00:00 |
| 3 | 2.10 | 2010-02-23 23:00:00 |
| 1 | 1.00 | 2010-02-23 19:00:00 |
| 2 | 1.00 | 2010-02-23 19:00:00 |
| 3 | 1.00 | 2010-02-23 19:00:00 |
+----------+-------+---------------------+
每次更新股价时,都会在表格中插入一个新行。
使用此结构,如何返回显示过去24小时内价格变化的查询?
期望的结果是:
+----------+------+------+------------+
| stock_id | then | now | difference |
+----------+------+------+------------+
| 3 | 1.00 | 3.30 | 2.30 |
| 2 | 1.00 | 3.25 | 2.25 |
| 1 | 1.00 | 0.05 | -0.95 |
+----------+------+------+------------+
最好的方法是什么?某种加入?子查询?
我认为我的目标是基本上查询一次以获取then
,再次查询以获取now
,然后以某种方式将它们全部粘合在一起。
编辑:我也需要考虑负面变化。
答案 0 :(得分:7)
好的,回到家,能够弄清楚这一点。
SELECT stock_id, t1.price AS `then`, t2.price AS `now`, ROUND(t2.price - t1.price, 2) AS `difference`
FROM (
SELECT stock_id, price, date FROM share_prices sp
WHERE date = (SELECT MIN(date) FROM share_prices sp2
WHERE date BETWEEN '2010/02/23 10:00:00'
AND '2010/02/24 10:00:00'
AND sp2.stock_id = sp.stock_id)
) t1
JOIN
(
SELECT stock_id, price, date FROM share_prices sp
WHERE date = (SELECT MAX(date) FROM share_prices sp2
WHERE date BETWEEN '2010/02/23 10:00:00'
AND '2010/02/24 10:00:00'
AND sp2.stock_id = sp.stock_id)
) t2 USING(stock_id)
ORDER BY `difference` DESC
使用来自2个子查询的结果,每个子查询都有自己的子查询,分别记录该范围的第一个和最后一个。
我使用integer
代表stock_id
,float
代表price
和timestamp
代表日期,因为可能存在问题(特别是MIN和MAX) )与其他数据类型。