简体   繁体   English

如何只获取一组数据中的最新记录?

[英]How to get only the most recent record on a group of data?

I need an help to solve this SQL problem: I've a dataset like this 我需要帮助来解决此SQL问题:我有一个像这样的数据集

Customer     Field A    Date

A            y        2015-01-21

A            z        2015-02-24

B            y        2015-02-01

B            g        2015-02-25

C            z        2015-02-25

C            x        2015-03-27

I would like to get ONLY one row per customer and only the most recent record. 我只希望每个客户获得一行,并且仅获得最新记录。 So, result must be: 因此,结果必须是:

A           z         2015-02-24

B           g         2015-02-25

C           x         2015-03-27

I think I need to get the DISTINCT of all customers and then JOIN them to the same table with a MAX clause on Date field. 我想我需要获取所有客户的DISTINCT,然后使用Date字段上的MAX子句将他们加入同一张表。 Something like this: 像这样:

SELECT DISTINCT customer FROM mytable a
INNER JOIN mytable b ON a.customer = b.customer

but I don't know how to continue... 但我不知道如何继续...

Or use a correlated sub-query to find a customer's max date: 或使用相关子查询来查找客户的最大日期:

SELECT *
FROM mytable a
WHERE Date = (select max(Date) from mytable b
              where a.customer = b.customer)

You can self-join on the max date of each customer 您可以在每个客户的最晚日期自动加入

SELECT a.*
FROM mytable a 
INNER JOIN 
(
  select customer, max(date_column) as mdate
  from mytable 
  group by customer 
) b ON a.customer = b.customer
   AND a.date_column = b.mdate

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

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