[英]Finding the difference between two values in the same column in MySQL
I have a simple table called that contains share prices in MySQL: 我有一个简单的表,其中包含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 |
+----------+-------+---------------------+
Every time a share price is updated, a new row is inserted into the table. 每次更新股价时,都会在表中插入一个新行。
With this structure, how can I return a query that shows the price change in the last 24 hours? 使用这种结构, 如何返回显示最近24小时内价格变化的查询?
The desired result would be: 理想的结果将是:
+----------+------+------+------------+
| 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 |
+----------+------+------+------------+
What's the best way to go about this? 最好的方法是什么? Some kind of join?
某种加盟? A sub-query?
子查询?
What I think I'm aiming for is to essentially query once to get then
, query again to get now
and then somehow glue it all together at the end. 我想我的目标是基本上一次查询得到
then
再次查询来获取now
然后以某种方式在最后把它粘在一起。
Edit: I need to account for negative changes too. 编辑:我也需要考虑负面变化。
Ok, got home, and was able to figure this out. 好的,回到家,并能够解决这个问题。
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
Uses the results from 2 subqueries, each with their own subquery to the first and last, respectively, record for that range. 使用2个子查询的结果,每个子查询分别具有针对该范围的第一个和最后一个记录的子查询。
I was using integer
for stock_id
, float
for price
and timestamp
for date, since there may be issues (notably with the MIN and MAX) with other data types. 我在
stock_id
中使用integer
,在price
使用float
,在日期上使用timestamp
,因为其他数据类型可能存在问题(尤其是MIN和MAX)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.