简体   繁体   English

分组依据与最大日期和另一列

[英]Group By with Max Date and another column

I have the following table.我有下表。

id ID user_id用户身份 file_id文件标识 completed完全的 updated更新
1 1 161 161 10 10 1 1 2022-10-11 2022-10-11
2 2 164 164 11 11 1 1 2022-10-12 2022-10-12
3 3 161 161 10 10 1 1 2022-10-12 2022-10-12
4 4 167 167 10 10 1 1 2022-10-10 2022-10-10
5 5 167 167 10 10 1 1 2022-10-11 2022-10-11
6 6 167 167 10 10 1 1 2022-10-12 2022-10-12

I want to select the row for each user having the max updated date for each file_id .我想 select 每个用户的行都有每个file_id的最大updated日期。

SELECT * FROM user_file
WHERE updated = (SELECT uf.updated FROM user_file uf GROUP BY uf.user_id,uf.file_id)

I have come up with this query but it returns an error "Subquery returns more than 1 row"我想出了这个查询,但它返回错误“子查询返回超过 1 行”

Maybe you want to check these out?也许你想看看这些?

Personally prefer the window function solution个人比较喜欢window function方案

SELECT a.*
  FROM (SELECT id, user_id, file_id, ...
               ROW_NUMBER() OVER (PARTITION BY file_id ORDER BY updated DESC) ranked_order
          FROM user_file) a
 WHERE a.ranked_order = 1 

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

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