dano
dano

Reputation: 73

Linq - Group by multiple tables

Using Linq to Sql how do i group the following 2 tables.

Orders Table:

CustomerID | Name   |Date            
1          | order1 | 2010-01-01  
2          | order2 | 2010-01-01
2          | order3 | 2010-04-01

Calls Table:

CustomerID | Name   |Date            
1          | call1 | 2010-01-01  
3          | call2 | 2010-06-01
2          | call3 | 2010-05-01

I want to group the two tables by date , Result:

Date       | Orders | Calls
2010-01-01 | 2      | 1
2010-04-01 | 1      | 0
2010-05-01 | 0      | 1
2010-06-01 | 0      | 1

i know how to group a single table ,

from o in Orders        
group o by o.Date.Date into og
select new {Date = og.Key,Orders= og.Count()};

how do i group both? thx!

Upvotes: 7

Views: 8358

Answers (2)

Shaun McCarthy
Shaun McCarthy

Reputation: 1690

You can use the Union method:

    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);
    }

This is very similar to the SQL you would write (a union of the two tables, and then an outer query to merge the results into a row)

Upvotes: 1

Johannes Rudolph
Johannes Rudolph

Reputation: 35741

Since both tables seem to have a similar structure I'd recommend projecting both into an equivalent form and then group on the concatenation of those two sets.

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)};

Due to the lazy nature of Linq2Sql this might actually be reduced to a single query. In the interest of performance I would make sure this is not a query from hell.

Upvotes: 9

Related Questions