简体   繁体   English

Sql到Linq难度 - 分组,有

[英]Sql to Linq difficulty - group by, having

I have the following query in SQL which I would like to convert to LINQ: 我在SQL中有以下查询,我想将其转换为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. 我有一个困难,如何将我的SQL查询中的最后一行写入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! 我认为可能主要的问题是,许多人将sql语句转换为where linq语句,但在我的情况下,我不认为有可能在linq语句组之后写另一个地方!

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! 也就是说,如果为每个孩子找到了配置文件X,那么,如果找到除了一个孩子之外的每个孩子的配置文件Y,那么它将无效!

Sounds like you want a where clause here... 听起来你想where这里使用where子句......

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM