使用Linq to Sql如何对以下2个表进行分组。
订单表:
CustomerID | Name |Date
1 | order1 | 2010-01-01
2 | order2 | 2010-01-01
2 | order3 | 2010-04-01
调用表:
CustomerID | Name |Date
1 | call1 | 2010-01-01
3 | call2 | 2010-06-01
2 | call3 | 2010-05-01
我想按日期对两个表进行分组,结果:
Date | Orders | Calls
2010-01-01 | 2 | 1
2010-04-01 | 1 | 0
2010-05-01 | 0 | 1
2010-06-01 | 0 | 1
我知道如何对单个表进行分组,
from o in Orders
group o by o.Date.Date into og
select new {Date = og.Key,Orders= og.Count()};
我如何分组? THX!
答案 0 :(得分:9)
由于两个表似乎都有类似的结构,我建议将两者都投射到等效的形式中,然后将这两个表的串联分组。
var orders = from o in Orders
select new { IsOrder = true, o.Date };
var calls = from c in Calls
select new { IsOrder = false, c.Date };
var result = from x in orders.Concat(calls)
group x by x.Date into og
select new {Date = og.Key, Orders= og.Count(o=>o.IsOrder), Calls = og.Count(c=>!c.IsTrue)};
由于Linq2Sql的惰性,这可能实际上减少为单个查询。为了表现,我会确保这不是地狱的问题。
答案 1 :(得分:1)
您可以使用Union方法:
var result =
(from c in Calls group c by c.Date into cg select new {Date = cg.Key, Calls = cg.Count(), Orders = 0})
.Union(from o in Orders group o by o.Date into og select new {Date = og.Key, Calls = 0, Orders = og.Count()})
.GroupBy(x => x.Date)
.Select(g => new {Date = g.Key, Calls = g.Max(r => r.Calls), Orders = g.Max(r => r.Orders)});
foreach (var row in result)
{
Trace.WriteLine(row);
}
这与您编写的SQL非常相似(两个表的并集,然后是将结果合并为一行的外部查询)