我有一张桌子
id | name | ts ------+------------+--------------------- 3812 | name1 | 2014-05-01 00:10:02 3900 | name1 | 2014-05-02 00:10:03 3838 | name2 | 2014-05-01 00:10:08 3893 | name3 | 2014-05-02 00:10:02 3933 | name2 | 2014-05-02 00:10:14 3977 | name3 | 2014-05-03 00:10:01 3985 | name1 | 2014-05-03 00:10:02 4006 | name2 | 2014-05-03 00:10:10 3815 | name3 | 2014-05-01 00:10:02
我需要执行一个只返回最新的选择(通过' table.ts'),并且只有一个条目用于字段中的每个DISTINCT值' table.name'
id | name | ts ------+------------+--------------------- 3977 | name3 | 2014-05-03 00:10:01 3985 | name1 | 2014-05-03 00:10:02 4006 | name2 | 2014-05-03 00:10:10
请帮我完成这项任务。
答案 0 :(得分:1)
select id, name, ts
from (
select id,
name,
ts,
max(ts) over (partition by name) as max_ts
from the_table
) t
where ts = max_ts;
答案 1 :(得分:0)
假设ID按顺序递增...
使用相同名称命名表中的表和列可能会导致以后出现问题...
Select max(n.ID), n.name, max(n.TS)
From Name n
group by n.name
但是如果ID不是顺序的 - 假设名称和ts是UNIQUE ......
Select a.id, a.name, a.ts
from name a
inner join (Select n.name, max(n.ts) mts from name n group by n.name) b
on A.Name = B.Name and A.TS = b.mts
答案 2 :(得分:0)
select b.id, a.name, a.ts
from
(
select name, max(ts) ts from table
group by name
) a
left join table b on
a.id=b.id