2

我在工作中被分配了一个使用 NHibernate 的新项目。我可以在 sql 中轻松编写的查询让我完全不知道如何在 linq 中执行此操作,这就是我被告知这样做的方式。

所以,这里是查询:

select  ts.BatchID, COUNT(distinct ts.UniqID) SurveyCount
from    TeleformStaging.TeleformStaging ts
where   ts.IsRescan = 0
and     not exists (select  bfr.BatchID
                    from    TeleformStaging.BatchesForRescan bfr
                    where   bfr.BatchTrack = ts.BatchID)
group by ts.BatchID
order by ts.BatchID

我相信我可以获得“分组依据”部分,但不知道子查询。

感谢您的任何建议...

4

3 回答 3

5

也许是这样的:

var result= (
        from ts in db.TeleformStaging
        where ts.IsRescan == false //if is a boolean else == 0
        && 
        !(
            from bfr in db.BatchesForRescan
            select bfr.BatchTrack
        ).Contains(ts.BatchID)
        orderby ts.BatchID
        group ts by ts.BatchID into g
        select new
        {
            BatchID=g.Key,
            SurveyCount=g.Select (x =>x.UniqID).Distinct().Count()
        }
    );

其中 db 是 linq 数据上下文

编辑

您也可以使用.Any(). 像这样:

var result= (
        from ts in db.TeleformStaging
        where ts.IsRescan == false //if is a boolean else == 0
        && 
        !(
            from bfr in db.BatchesForRescan
            where ts.BatchID==bfr.BatchTrack
            select bfr.BatchTrack
        ).Any()
        orderby ts.BatchID
        group ts by ts.BatchID into g
        select new
        {
            BatchID=g.Key,
            SurveyCount=g.Select (x =>x.UniqID).Distinct().Count()
        }
    );

编辑 1

有用的链接:

于 2012-04-10T13:40:22.640 回答
0
from fs in context.TeleformStaging
where !ts.IsRescan && !context.BatchesForRescan.Any(bfr=>bfr.BatchTrack == ts.BatchID)
group ts by ts.BatchID into g
    select new
    {
        BatchID=g.Key,
        SurveyCount=g.Select (x =>x.UniqID).Distinct().Count()
    }

与分组

于 2012-04-10T13:41:54.343 回答
0

LINQ 稍微颠倒过来,但确实提供了一些 lambda 表达式的复杂性;这看起来如何:

var result = from ts in TeleformStaging.TeleformStaging
                where !ts.IsRescan && !TeleformStaging.BatchesForRescan.Any(bfr => bfr.BatchID == ts.BatchID)
                group ts by ts.BatchID into tsGrouped
                orderby tsGrouped.Key
                select new
                {
                    BatchId = tsGrouped.Key,
                    SurveyCount = tsGrouped.Select(x => x.UniqID).Distinct().Count()
                };
于 2012-04-10T13:48:32.123 回答