如何根据其他列数据过滤掉相似的行(在某些列上相等)
我如何选择名字和姓氏上不同的所有行,并且在有重复的地方选择具有较高SomeDate的行,然后选择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 |
我如何
- 在T-SQL从 DataTable 中实现此目的
- 使用 C#
How would I select all rows distinct on Forename and Surname and where there's a duplicate select the one with the higher SomeDate, then Id if still duplicates e.g.
For:
| 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 |
Results in:
| 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 |
How could I achieve this in
- T-SQL
- From a DataTable using C#
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设 SQL Server 2005+,使用:
一个有风险的方法是:
Assuming SQL Server 2005+, use:
A risky approach would be:
我倾向于对非分组值使用子选择。
或者您可以在 WHERE 子句中对其进行过滤:
恐怕这两种方法都不会非常有效,但如果需要的话,索引调整会改善这种情况。
对于数据表示例,您基本上会做同样的事情。
I'd tend to use subselects for the non-grouped values.
Or you can filter it in the WHERE clause:
I'm afraid neither will be terribly efficient, but index toning will ameliate that if needed.
For a datatable example, you'd do essentially the same thing.