SQL查询:仅显示每个集合中的最新ID [英] SQL Query: Display only latest Id from each set
问题描述
我有以下SQL表:
Name Description Id UserId CreatedDate
UserSet1 Desc1 1 Abc 06/01/2018
UserSet1 Desc2 2 Def 06/02/2018
UserSet2 Desc for 2 5 NewUser 06/04/2018
UserSet2 Desc for 2 7 NewUser 06/19/2018
我要从上表中提取的只是每个名称的最新ID,以便获得以下输出
What I want to extract from the above table is just the latest Id for each Name so that I could get the following output
Name Description Id UserId CreatedDate
UserSet1 Desc2 2 Def 06/01/2018
UserSet2 Desc for 2 7 NewUser 06/19/2018
由于Id 2& 7是表中UserSet1&的最新条目. UserSet2,我想显示它而不是表中的所有条目.
Since Id 2 & 7 are the latest entries in the table for UserSet1 & UserSet2, I would like to display that instead of all the entries in the table.
任何输入都如何获得所需的结果.
Any inputs how can I get the desired result.
我愿意接受直接返回输出的解决方案或任何linq(C#)解决方案.即返回整个数据集,然后使用linq过滤上述内容.
I am open for solutions directly returning the output or any linq (C#) solutions as well. Ie returning the entire dataset and then using linq to filter the above.
推荐答案
感谢大家指出正确的方向.我已经使用下面的Linq和C#代码进行了此工作:
Thanks everyone for pointing to right direction. I have got this working with the below code of Linq and C#:
var results = response.GroupBy(row => row.Name)
.SelectMany(g => g.OrderByDescending(row => row.Id).Take(1));
对于最初的测试,这似乎是可行的.让我知道您是否认为这已经成为问题.
For the initial tests this seems to be working. Let me know if you think this has come issues.
这篇关于SQL查询:仅显示每个集合中的最新ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!