16

How can I write a linq to entities query that includes a having clause?

For example:

SELECT State.Name, Count(*) FROM State
INNER JOIN StateOwner ON State.StateID = StateOwner.StateID
GROUP BY State.StateID
HAVING Count(*) > 1
Jeremy
  • 8,073
  • 17
  • 52
  • 68

3 Answers3

28

Any reason not to just use a where clause on the result?

var query = from state in states
            join stateowner in stateowners
              on state.stateid equals stateowner.stateid
            group state.Name by state.stateid into grouped
            where grouped.Count() > 1
            select new { Name = grouped.Key, grouped.Count() };
Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
3

I believe you can use a GroupBy followed by a Where clause and it will translate it as a Having. Not entirely sure though.

Andrew Flanagan
  • 4,237
  • 2
  • 23
  • 37
  • 2
    For MySql it will cause inner SELECT with outer WHERE, not HAVING. So it will cause performance issue. – Yuri Jan 18 '13 at 11:28
0

If you want to compare a variable that is not in the group by (Ex: age), then it would be:

var duplicated = (
                  from q1 in db.table1
                  where (q1.age >= 10 )
                  group q1 by new { q1.firstName, q1.lastName } into grp
                  where (grp.Count() > 1 )
                  select new 
                   {
                     firstName= grp.Key.firstName,
                     lastName = grp.Key.lastName,
                   }
                 );