我正在运行mysql-array.findIndex(item => _.isEqual(item, testObject)) >= 0
-数据库。
我有下表:
10.1.39-MariaDB - mariadb.org binary
我正在使用mysql计算退货:
| id | date | api_endpoint | ticker | open | high | low | close | volume |
|------|---------------------|--------------|--------|-----------|-----------|-----------|-----------|-----------|
| 18 | 2019-08-07 00:00:00 | daily | AAPL | 195.41000 | 199.56000 | 193.82000 | 199.04000 | 33364400 |
| 19 | 2019-08-06 00:00:00 | daily | AAPL | 196.31000 | 198.07000 | 194.04000 | 197.00000 | 35824800 |
| 20 | 2019-08-05 00:00:00 | daily | AAPL | 197.99000 | 198.65000 | 192.58000 | 193.34000 | 52393000 |
| 21 | 2019-08-02 00:00:00 | daily | AAPL | 205.53000 | 206.43000 | 201.62470 | 204.02000 | 40862100 |
| 44 | 2019-08-01 00:00:00 | monthly | AAPL | 213.90000 | 218.03000 | 206.74000 | 208.43000 | 54017900 |
| 5273 | 1999-09-07 00:00:00 | monthly | AAPL | 73.75000 | 77.93800 | 73.50000 | 76.37500 | 246198400 |
上面的查询在我的表中添加了列SELECT *
,(CLOSE - (SELECT (t2.close)
FROM prices t2
WHERE t2.date < t1.date
ORDER BY t2.date DESC
LIMIT 1 ) ) / (SELECT (t2.close)
FROM prices t2
WHERE t2.date < t1.date
ORDER BY t2.date DESC
LIMIT 1 ) AS daily_returns
FROM prices
。
我想得到daily_returns
。我尝试使用top 5 highest daily_returns
,但是,这不适用于计算列。
有人建议如何获得前5名最高的ORDER BY
吗?
答案 0 :(得分:3)
使用MySQL variable存储前一天的close
值。将其与close
值与当前行的值进行比较以进行计算。
SELECT
*
FROM (
SELECT
prices.*,
(`close` - @old_close) / @old_close AS daily_return, -- Use @old_case, currently it has value of old row, next column will set it to current close value.
@old_close:= `close` -- Set @old_close to close value of this row, so it can be used in next row
FROM prices,
(SELECT @old_close:= 0 as o_c) AS t -- Initialize old_close as 0
ORDER BY `date` ASC -- return is calculated based on last day close, so keep it sorted based on ascending order of date
) AS tt
ORDER BY daily_return DESC
LIMIT 5;