我正在尝试构建一个按Name
和Year
排序的查询,过滤具有更高年份的重复项并将这些记录返回到表中。我的数据目前看起来像这样:
ID-----Name-----Year
1 Bob 2010
2 John 2014
3 Bob 2004
4 Eric 2005
数据应主要按Name
排序,然后按Year
按降序排序,如下所示:
ID-----Name-----Year
3 Bob 2004
1 Bob 2010
4 Eric 2005
2 John 2014
然后重复的Name
条记录应该过滤,只返回最低Year
,如下所示:
ID-----Name-----Year
3 Bob 2004
4 Eric 2005
2 John 2014
我尝试了SELECT DISTINCT
和HAVING COUNT
之类的内容,但似乎无法得到它。可能缺少一些简单的东西。有什么帮助吗?
答案 0 :(得分:5)
select ID, Name, Year
from (
select ID, Name, Year, Rank() over (partition by Name order by year) as Rank
from MyTable
) t
where Rank = 1
如果您无法使用PARTITION
,则可以执行此操作:
select m.ID, m.Name, m.Year
from (
select Name, min(Year) as MinYear
from MyTable
group by Name
) mm
inner join MyTable m on mm.Name = m.Name and mm.MinYear = m.Year
答案 1 :(得分:1)
SELECT Name, MIN(Year) FROM table
GROUP BY Name
ORDER BY Name ASC
答案 2 :(得分:0)
假设MySQL
select min(id), name, min(year)
from (
select distinct t1.id, t1.name, t2.year
from tbl t1, tbl t2
odrer by t1.name, t2.year
) T
group by name