我有一个带有名称和日期的表格。我想为每个名称返回最后日期(最近)的列。 R中的应与此类似:
date <- sample(seq(as.Date('2018/01/01'), as.Date('2019/01/01'), by="day"), 12)
name <- sample(c("carol", "steph", "bob"), 12, replace = T)
df <- tibble(name, date)
df %>%
group_by(name) %>%
mutate(last_date = max(date)) %>%
arrange(name)
输入:
输出:
答案 0 :(得分:1)
使用相关子查询
select t1.* from table t1
where t1.last_date= (
select max(last_date) from table t2 where t2.name=t1.name
)
或者您可以使用row_number()
select * from
(
select *, row_number() over(partition by name order by last_date) rn
from table_name
) t where t.rn=1
看到更改后,您似乎需要在查询下面
select t.name,t.date,t1.last_date from table_name t
join
(
select name,max(last_date) as last_date from table_name
group by name
) t1 on t.name=t1.name