简体   繁体   English

如何只为每个用户选择最新的行?

[英]How to select only the latest rows for each user?

My table looks like this: 我的表看起来像这样:

id  | user_id | period_id | completed_on
----------------------------------------
1   | 1       | 1         | 2010-01-01
2   | 2       | 1         | 2010-01-10
3   | 3       | 1         | 2010-01-13
4   | 1       | 2         | 2011-01-01
5   | 2       | 2         | 2011-01-03
6   | 2       | 3         | 2012-01-13
... | ...     | ...       | ...

I want to select only the latest users periods entries, bearing in mind that users will not all have the same period entries. 我想只选择最新的用户期间条目,记住用户不会都有相同的期间条目。

Essentially (assuming all I have is the above table) I want to get this: 基本上(假设我只有上表)我想得到这个:

id  | user_id | period_id | completed_on
----------------------------------------
3   | 3       | 1         | 2010-01-13
4   | 1       | 2         | 2011-01-01
6   | 2       | 3         | 2012-01-13

Both of the below queries always resulted with the first user_id occurance being selected, not the latest (because the ordering happens after the rows are selected from what I understand): 以下两个查询总是在第一个user_id出现被选中时产生,而不是最新的(因为在从我理解的行中选择行之后排序发生):

SELECT
    DISTINCT user_id,
    period_id,
    completed_on
FROM my_table
ORDER BY
    user_id ASC,
    period_id DESC

SELECT *
FROM my_table
GROUP BY user_id
ORDER BY
    user_id ASC,
    period_id DESC

Seems like this should work using MAX and a subquery: 看起来这应该使用MAX和子查询:

SELECT t.Id, t.User_Id, t.Period_Id, t.Completed_On
FROM my_table t
   JOIN (SELECT Max(completed_on) Max_Completed_On, t.User_Id
         FROM my_table
         GROUP BY t.User_ID
         ) t2 ON
      t.User_Id = t2.User_Id AND t.Completed_On = t2.Max_Completed_On

However, if you potentially have multiple records where the completed_on date is the same per user, then this could return multiple records. 但是,如果您可能有多个记录,其中每个用户的completed_on日期相同,则可能会返回多个记录。 Depending on your needs, potentially adding a MAX(Id) in your subquery and joining on that would work. 根据您的需要,可能会在子查询中添加MAX(Id)并加入其中。

try this: 尝试这个:

SELECT t.Id, t.User_Id, t.Period_Id, t.Completed_On
FROM table1 t
JOIN (SELECT Max(completed_on) Max_Completed_On, t.User_Id
FROM table1 t
GROUP BY t.User_ID) t2 ON t.User_Id = t2.User_Id AND t.Completed_On = t2.Max_Completed_On

DEMO HERE 在这里演示

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

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