我已经为此工作了大约两天,似乎无法弄清楚,所以我希望获得帮助。
我有两个表:
mysql> select id, date, volume, symbol_id from control_quotedaily limit 5;
+-------+---- -------+----------+-----------+
| id | date | volume | symbol_id |
+-------+------------+----------+-----------+
| 13263 | 2017-11-02 | 7800191 | AXISBANK |
| 13264 | 2017-11-02 | 9303981 | SBIN |
| 13265 | 2017-11-02 | 8013536 | HDFCBANK |
| 13266 | 2017-11-03 | 9642624 | AXISBANK |
| 13267 | 2017-11-04 | 19642327 | AXISBANK |
+-------+------------+----------+-----------+
5 rows in set (0.00 sec)
14 rows in set (0.01 sec)
mysql> select * from control_oidaily
+-----------+------------+-------------+--------------+
| symbol_id | date | expiry_date | val_in_lakhs |
+-----------+------------+-------------+--------------+
| AXISBANK | 2017-11-02 | 2017-11-30 | 166881.8 |
| AXISBANK | 2017-11-02 | 2017-12-28 | 2676.84 |
| AXISBANK | 2017-11-02 | 2018-01-25 | 97.13 |
| HDFCBANK | 2017-11-02 | 2017-11-30 | 76351.11 |
| HDFCBANK | 2017-11-02 | 2017-12-28 | 1509.48 |
| HDFCBANK | 2017-11-02 | 2018-01-25 | 0 |
| SBIN | 2017-11-02 | 2017-11-30 | 88654.3 |
| SBIN | 2017-11-02 | 2017-12-28 | 1060.51 |
| SBIN | 2017-11-02 | 2018-01-25 | 0 |
| AXISBANK | 2017-11-03 | 2017-11-30 | 87640.06 |
+-----------+------------+-------------+--------------+
因此,对于control_quotedaily表中的每个报价,这就是我想要的:
例如:对于日期2017-11-02,最接近的到期日期是2017-11-30,我希望返回val_in_lakhs(76351.11)。
这是我正在尝试的:
select o.date, o.expiry_date as expiry_date, o.symbol_id, q.date, q.symbol_id, o.val_in_lakhs, q.tottrdval, q.volume, q.symbol_id
FROM control_oidaily o
JOIN ( select o.date, MIN(expiry_date) as expiry_date, symbol_id
FROM control_oidaily o
GROUP by o.date,o.symbol_id
ORDER BY o.date asc) as ed
ON ed.date = o.date
AND ed.symbol_id = o.symbol_id
AND ed.expiry_date = o.expiry_date
JOIN control_quotedaily q
ON q.date = ed.date
AND q.symbol_id = ed.symbol_id
这是我期望的输出:
+-------+------------+----------+-----------+--------------+--------------+
| id | date | volume | symbol_id | expiry_date | val_in_lakhs |
+-------+------------+----------+-----------+--------------+--------------+
| 13263 | 2017-11-02 | 7800191 | AXISBANK | 2017-11-30 | 166881.8 |
| 13264 | 2017-11-02 | 9303981 | SBIN | 2017-11-30 | 88654.3 |
| 13265 | 2017-11-02 | 8013536 | HDFCBANK | 2017-11-30 | 76351.11 |
| 13266 | 2017-11-03 | 9642624 | AXISBANK | 2017-11-30 | 87640.06 |
+-------+------------+----------+-----------+--------------+--------------+
答案 0 :(得分:0)
closest_expiry_date
和expiry_date
的{{1}}(最小值symbol_id
) }表。date
和control_oidaily
上的control_quotedaily
表结合起来,以获取symbol_id
表中每一行的最近值。
date
表联接,在control_quotedaily
,control_oidaily
(具有最接近的到期日期)和date
上进行匹配,以得到{ {1}}。您可能需要以下查询:
expiry_date