【问题标题】:Better way of grouping rows by the latest entry within a group using LINQ使用 LINQ 按组中的最新条目对行进行分组的更好方法
【发布时间】:2011-07-06 13:41:31
【问题描述】:

假设我有一个包含 3 个列的表:ActionId、uid 和 created。

我想按 uid 对操作进行分组,但是每次将新操作插入组(按 uid)时,它都会将组推到顶部,并且该组中的各个行排序。

这是我在 SQL 中提出的:

select * from actions as a
inner join 
(   
    select aa.[uid], MAX(aa.[created]) as maxcreated 
    from actions as aa
    group by aa.[uid]
) as a2 on a2.uid = a.uid
order by a2.maxcreated desc, a.created desc

有没有更好的方法在 SQL 中实现这一点,以及如何在 LINQ 中做到这一点?

【问题讨论】:

  • 你是分组还是订购?分组意味着您将获得基于分组的汇总数据,即 count()、sum()、avg()。
  • @Narnian - 有效地根据 Uid 分组,但根据组内的最近日期对组进行排序。想象一下 uid 字段就像一个 threadId,将操作分组到线程中。我希望这些动作在线程组中一起显示,但是每当插入一个动作时,具有相同 uid 的组就会被推到顶部。

标签: sql linq tsql


【解决方案1】:

所以您希望每个组在内部排序,并且这些组按最新值排序,对吗?好吧,我想我们可以做到……

var query = from action in actions
            group action by action.Uid into g
            orderby g.Max(action => action.Created) descending
            select new { Uid = g.Key,
                         Actions = g.OrderByDescending(action => action.Created) };

foreach (var group in query)
{
    Console.WriteLine("Uid: {0}", group.Uid);
    foreach (var action in group.Actions)
    {
        Console.WriteLine("  {0}: {1}", action.Created, action.ActionId);
    }
}

【讨论】:

  • 甜蜜!那是否有效地与我的 t-sql 语句相同?当我尝试将它逆向工程到我的 t-sql 头部时,它似乎略有不同;)
【解决方案2】:

对于 SQL,在 SELECT 语句中获取排序列

SELECT *, (SELECT MAX(created) FROM actions a2 where a.uid = a2.uid) AS MaxCreated
FROM actions a
ORDER BY MaxCreated desc, a.created desc

SELECT *
FROM actions a
ORDER BY (SELECT MAX(created) FROM actions a2 where a.uid = a2.uid) desc, a.created desc

(刚刚修复了第一个查询中的错误)

这是我的 linq:

var actions = (from a in actions                
               orderby ((from a2 in actions
                         where a2.UserID == a.UserID
                         select a2.created).Max ()) descending, a.created descending
               select a);

【讨论】:

  • 你更喜欢这两个选项中的哪一个,你有我可以与 Jon Skeet 的版本比较的 LINQ 版本吗?
  • 任何一个都可以。第二个将 MaxCreated 排除在您的结果之外,因此可能更可取。
猜你喜欢
  • 2016-07-24
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 2011-07-22
  • 1970-01-01
  • 1970-01-01
  • 2021-02-25
  • 2021-02-09
相关资源
最近更新 更多