如何选择 Forename 和 Surname 上的所有不同行,如果有重复,请选择 SomeDate 更高的行,然后< strong> Id 如果仍然重复,例如
有关:
| Id | Forename | Surname | SomeDate | ---------------------------------------- | 1 | Bill | Power | 2011-01-01 | | 2 | James | Joyce | 2011-02-01 | | 3 | Peter | Lennon | 2011-03-01 | | 4 | John | Sellers | 2011-04-01 | | 5 | James | Joyce | 2011-05-01 | | 6 | Peter | Lennon | 2011-03-01 |
结果:
| Id | Forename | Surname | SomeDate | ---------------------------------------- | 1 | Bill | Power | 2011-01-01 | | 4 | John | Sellers | 2011-04-01 | | 5 | James | Joyce | 2011-05-01 | | 6 | Peter | Lennon | 2011-03-01 |
我怎样才能在
中实现这一目标答案 0 :(得分:2)
假设SQL Server 2005+,请使用:
SELECT x.id,
x.forename,
x.surname,
x.somedate
FROM (SELECT t.id,
t.forename,
t.surname,
t.somedate,
ROW_NUMBER() OVER (PARTITION BY t.forename, t.surname
ORDER BY t.somedate DESC, t.id DESC) AS rank
FROM TABLE t_ x
WHERE x.rank = 1
风险方法是:
SELECT MAX(t.id) AS id,
t.forename,
t.surname,
MAX(t.somedate) AS somedate
FROM TABLE t
GROUP BY t.forename, t.surname
答案 1 :(得分:1)
我倾向于对未分组的值使用子选择。
SELECT Forename, Surname,
(SELECT TOP 1 Id FROM myTable mt WHERE mt.Forename = m.Forename AND mt.Surname = m.Surname
ORDER BY m.SomeDate DESC) AS Id
(SELECT TOP 1 SomeDate FROM myTable mt WHERE mt.Forename = m.Forename AND mt.Surname = m.Surname
ORDER BY m.SomeDate DESC) AS SomeDate
FROM myTable m
GROUP BY Forename, Surname
或者你可以在WHERE子句中过滤它:
SELECT Id, Forename, Surname, SomeDate
FROM myTable m
WHERE m.Id = (SELECT TOP 1 Id FROM myTable mt WHERE mt.Forename = m.Forename AND mt.Surname = m.Surname
ORDER BY m.SomeDate DESC)
我担心两者都不会非常高效,但如果需要的话,指数调整会改善它。
对于数据表示例,您基本上会做同样的事情。
var recs = from record in dataTable
where record.Id ==
(from rec in dataTable
where rec.Forename == record.Forename && rec.Surname == record.Surname
orderby rec.SomeDate descending
select rec.Id).First()
select record;