Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 954
dano Avatar asked Aug 08 '10 18:08

dano


1 Answers

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.

like image 182
Johannes Rudolph Avatar answered Sep 19 '22 16:09

Johannes Rudolph