Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql to Linq difficulty - group by, having

I have the following query in SQL which I would like to convert to LINQ:

select profile_id from t
where child_id in (1, 2 ,3, ...) //this will be a list of integers CHILDREN
group by profile_id
having count(distinct child_id) = 3

I am having a difficulty how to write the last line in my sql query into linq. The following is my work so far:

public IQueryable<ProfileChildRelationship> GetPCRelByCids(List<int> children)
    {
        var query = from pcr in this._entities.ProfileChildRelationships
                    where children.Contains(pcr.pcChildIDF)
                    group pcr by pcr.pcProfileIDF into g
                    ??? having ...?
                    select pcr;

        return query;
    }

I think that may main problem is that many convert a having sql statement into a where linq statement, but in my case i do not think it is possible to write another where after the group by linq statement!

Update:

The situation: I have a number of children, each of which has many different profiles, (some may be the same). A user will select a number of children, from which I would like to derive their common profiles. That is, if profile X is found for EVERY child, than I will get it, if profile Y is found for every child except one, than it would be invalid!

like image 772
test Avatar asked May 01 '12 13:05

test


1 Answers

Sounds like you want a where clause here...

var query = from pcr in this._entities.ProfileChildRelationships
            where children.Contains(pcr.pcChildIDF)
            group pcr by pcr.pcProfileIDF into g
            where g.Select(x => x.ChildId).Distinct().Count() == 3
            select g.Key; // This is the profile ID
like image 95
Jon Skeet Avatar answered Nov 01 '22 04:11

Jon Skeet