1

I have a table like this

+------+-------+-----------+-------------+
| code | price | perct_off | date_review |
+------+-------+-----------+-------------+
| 0001 |  1500 |        40 | 2017-12-30  |
| 0001 |  1500 |        40 | 2018-02-15  |
| 0001 |  2000 |        25 | 2018-07-31  |
| 0002 |  3000 |        45 | 2018-03-20  |
| 0002 |  5000 |        20 | 2018-08-01  |
| 0003 |  3000 |        40 | 2018-01-16  |
+------+-------+-----------+-------------+

and I want to have only the records with the max date for every code. The iutput must be:

+------+-------+-----------+-------------+
| code | price | perct_off | date_review |
+------+-------+-----------+-------------+
| 0001 |  2000 |        25 | 2018-07-31  |
| 0002 |  5000 |        20 | 2018-08-01  |
| 0003 |  3000 |        40 | 2018-01-16  |
+------+-------+-----------+-------------+

When I try:

SELECT DISTINCT
    (code), price, perct_off, MAX(date_review)
FROM `table01`
GROUP BY code

I've got this output

+-------+--------+------------+-------------------+
| code  | price  | perct_off  | max(date_review)  |
+-------+--------+------------+-------------------+
| 0001  |   1500 |         40 | 2018-07-31        |
| 0002  |   3000 |         45 | 2018-08-01        |
| 0003  |   3000 |         40 | 2018-01-16        |
+-------+--------+------------+-------------------+ 

How can I get the rigth output?

Thanks in advance.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
Emilio Galarraga
  • 659
  • 1
  • 8
  • 14
  • This answer will help you out: https://stackoverflow.com/questions/12113699/get-top-n-records-for-each-group-of-grouped-results/12117654#12117654 – LukasS Aug 06 '18 at 02:17

2 Answers2

0

One canonical way to do this is to join to subquery which finds the most recent date for each code:

SELECT t1.*
FROM table01 t1
INNER JOIN
(
    SELECT code, MAX(date_review) AS max_date_review
    FROM table01
    GROUP BY code
) t2
    ON t1.code = t2.code AND t1.date_review = t2.max_date_review;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Optimized solution:

SELECT
  t1.code,
  t1.price,
  t1.perct_off,
  t1.date_review
FROM t t1
  LEFT JOIN t t2 ON
    t1.code = t2.code 
    AND t1.date_review < t2.date_review
WHERE t2.date_review IS NULL;
Alexander Yancharuk
  • 13,817
  • 5
  • 55
  • 55