views:

249

answers:

2

How is something like this done in linq? It has filter criteria on the JOIN.

This is taken from this question: http://stackoverflow.com/questions/1401889/sql-filter-criteria-in-join-criteria-or-where-clause-which-is-more-efficient

select salesman.salesmanid, max(sales.quantity)
from salesman
inner join sales  on salesman.salesmanid =sales.salesmanid 
              and sales.salesdate < salesman.promotiondate
group by salesman.salesmanid

Thanks

+1  A: 

You can't join on anything other than equals, but that's probably not what you want here anyway. I would contend that the SQL query is awkwardly written and that the date comparison should be in a WHERE clause, but I suppose that's subjective. Anyway, that's the only way to do it in Linq:

var results =
    from sm in salesman
    join s in sales on sm.salesmanid equals s.salesmanid
    where s.salesdate < sm.promotiondate
    group s by s.salesmanid into g
    select new { salesmanid = g.Key, maxsales = g.Max(s => s.quantity) };

Note - corrected typo on group line

Aaronaught
I just read somewhere that you can use a where clause straight after a join for performance increase (filtering) and then after the where clause, continue to join your other tables. So I'm going to try that out now.I am trying to apply this method to an existing database, which I have come across a sql query with join filtering. It has about 2 million records, with the tables that I want to join. Doing a straight where clause instead of using filtered join hits the performance REALLY REALLY hard. Thanks for your answer and I'm going to try it out now. I'll let you know how it goes.
Mike
@Mike - hmm, it shouldn't matter if the condition is part of the `JOIN` or the `WHERE`, all that really matters to the DB server is that the right columns are indexed. I prefer to write all join conditions in the actual join clause, but that's only because it's easier to do correctly.
Aaronaught
It didn't seem to make any difference. As you said. Thanks again.
Mike
A: 

Assuming you have navigation properties between your tables, you can leave the join to entity framework.

var results = from s in salesmen
              group s by s.salesmanid
              select new
              {
                  s.salesmanid,
                  maxsales = s.sales
                      .where(x => s.salesdate < x.promotiondate)
                      .max(x => x.quantity)
              };
Sander Rijken