简体   繁体   中英

Get closest value lower than a specific value and group by

Is there a possibility to get the closest value lower than a specific value with a group function without a join?

date          productId    stock
2014-12-27    1            10
2014-12-31    1            20
2015-01-05    1            30
2014-12-28    2            10
2015-01-04    2            20

The value is for example the date and should be lower than 2015-01-01 but the highest date value and the result should be ordered by the stock sac, so the result should be:

date          productId    stock
2014-12-28    2            10
2014-12-31    1            20

Of course, this could be solves with a join, but a join is slower in large tables, isn't it?

You're looking for the last day of 2014, it seems, for each distinct product id.

You do that with

             SELECT MAX(date) date, product_id   
               FROM yourtable
              WHERE date < '2015-01-01'
           GROUP BY product_id

That gives you a collection of date, product_id . A compound index on (date, product_id) will make this query very efficient to evaluate.

Then you join that to your main table, like so.

SELECT a.*
  FROM yourtable AS a
  JOIN (
             SELECT MAX(date) date, product_id   
               FROM yourtable
              WHERE date < '2015-01-01'
           GROUP BY product_id
       ) AS b USING(date,product_id)
ORDER BY a.product_id, a.date

and that retrieves the detail records for the last item in 2014. The same compound index will accelerate the JOIN.

You're worried about JOIN performance, and that's legitimate. But it can be improved with proper indexing. There really isn't a better way to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM