在给定日期之前有效查找多个最近日期?

时间:2018-04-14 07:04:28

标签: sql postgresql

以下查询需要1.5秒,因为我需要运行数千次,我想优化它。基本上我尝试找到小于或等于提供日期数组的第一个日期(例如['2016-01-01', '2017-01-01', '2018-01-01'])。现在我分别做每个日期:

SELECT date FROM date_history
     WHERE ticker = 'APPL' AND date <= %(date)
     ORDER BY date DESC LIMIT 1;

我觉得如果我可以重用日期排序或者在这些行下面的东西可能会更快但我想不出一个好方法来做到这一点。任何有关如何加快速度的建议都将不胜感激!

1 个答案:

答案 0 :(得分:2)

您可以使用AVCaptureDevice.default(for: AVMediaType.video) { let input = AVCaptureDeviceInput(device: captureDevice) session.addInput(input) }

ROW_NUMBER

或者WITH cte(d) AS ( VALUES ('2016-01-01'::date) ,('2017-01-01'::date) ,('2018-01-01'::date) --Or unnest array_variable WITH ORDINALITY ), cte2 AS ( SELECT d.date, c.d, ROW_NUMBER() OVER(PARTITION BY c.d ORDER BY d.date DESC) AS rn FROM cte c LEFT JOIN date_history d ON d.date <= c.d WHERE d.ticker = 'APPL' ) SELECT c.d, d.date AS max_date_before FROM cte2 WHERE rn = 1 ORDER BY c.d ASC; 和相关的子查询:

LEFT JOIN LATERAL