简体   繁体   English

仅获取每个代码的最新日期的记录

[英]Get only the records with most recent date to every code

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: Iutput必须为:

+------+-------+-----------+-------------+
| 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. 提前致谢。

One canonical way to do this is to join to subquery which finds the most recent date for each code : 做到这一点的一种典型方法是加入子查询,该子查询查找每个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;

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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