LINQ查询请帮忙。为每个 FK 选择最新记录
假设我有一个如下所示的表:
Id CheckboxId Selected DateCreated
1 1 1 1/1/2010
2 2 1 1/2/2010
3 1 0 1/3/2010
4 3 1 1/4/2010
5 3 0 1/5/2010
CheckboxId 是一个 FK,该表只是选中或取消选中框的历史记录。
我想要获取的是每个 CheckboxId 的最新记录。在我的演示表中,我需要第 2、3 和 5 行。您将如何完成此操作?另外,我确信这就像查询开头的“where”一样简单,但如果也可以将其修改为仅获取指定日期之前的记录,那就太棒了。
我无法弄清楚如何在 SQL 中编写查询来执行此操作,这使得链接查询变得不可能。我确信它必须是从不同 checkboxIds 的子查询中选择的,再加上一个 group by 或其他东西,但我的 SQL 并不是那么好。
非常感谢您的帮助。
Let's say I have a table that looks like this:
Id CheckboxId Selected DateCreated
1 1 1 1/1/2010
2 2 1 1/2/2010
3 1 0 1/3/2010
4 3 1 1/4/2010
5 3 0 1/5/2010
CheckboxId is a FK and the table is just a history of when the boxes are checked or unchecked.
What I want to get is the most recent record for each CheckboxId. In the case of my demo table I want rows 2, 3, and 5. How would you accomplish this? Also I'm sure this is as easy as a "where" at the beginning of the query but if it could also be modified to only get records before a specified date that would be fantastic.
I'm having trouble figuring out how I would write a query to do this in SQL and it's making a link query impossible. I'm sure it has to be a selection from a sub query of distinct checkboxIds coupled with a group by or something but my SQL just isn't that great.
Many thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
应该是这样的:
然后你可以这样做:
Should be something like this:
Then you can do:
使用子查询获取每个
CheckBoxId
的最新条目,然后连接到该表以获取其余结果:我将其作为练习留给读者转换为 LINQ :)
Use a subquery to get the most recent entries per
CheckBoxId
, then join to that table to get the rest of the results:I leave it as an exercise for the reader to convert to LINQ :)
根据您的评论,您希望在指定日期选择的复选框
将为您提供这些结果,如果您想通过
CheckboxId
将其限制为最新,只需添加此内容,您可以循环结果并获取每个结果的最新结果像这样的复选框
According to your comment you want checkboxes selected on a specified date
will get you those results, if you want to limit it to the latest by
CheckboxId
just add thisyou could loop the results and grab the latest for each checkboxid like so