简体   繁体   English

如何在LINQ中的复杂group by上的聚合上使用having子句并在LINQ中加入查询

[英]How do I use the having clause on an aggregate in a complex group by and join query in LINQ

I have reviewed a lot of the questions and answers here but cant seem to find what I need. 我在这里查看了很多问题和答案,但似乎找不到我需要的东西。 I have the following sql below which I am having real trouble getting into a LINQ statement. 我有以下sql,在进入LINQ语句时遇到真正的麻烦。 The specific issue is that for one of the fields I am using a CASE statement both in the select and has part of the HAVING clause. 特定的问题是,对于其中一个字段,我在select中使用了CASE语句,并且具有HAVING子句的一部分。 Various reasons why i needed to do this but I cant seem to reproduce it in LINQ. 我需要这样做的各种原因,但我似乎无法在LINQ中重现。

Here is the sql: 这是SQL:

select Count (DetailID) as MonthCount , StoreID, DetailID, SUM(Amount ) as AnnualAmount, PAYear, MIN(CASE when ExportFlag = 'SUCCESS' then 1 when ExportFlag is NULL or  ExportFlag = '' then 0 else - 1 end) as ExpFlag
from Input_Financials
inner join DestinationDetail cdd on cdd .ID = Financials.DetailID
group by StoreID, DetailID, PAYear
Having MIN (CASE when ExportFlag = 'SUCCESS' then 1 when ExportFlag is NULL then 0 else -1 end ) = 0
and Count (*) >= 1
order by PAYear 

This was my best attempt linq statment but you will notice that I dont have the equivalent of the having clause which aggregates the ExportFlag value (which is very important) 这是我最大的尝试linq语句,但是您会注意到我没有等效的hading子句来聚合ExportFlag值(这很重要)

   var query =
               from inf in inputActs
               join cgrdets in cgrDetails on inf.DestinationDetailID equals cgrdets.ID
               let export = (inf.ExportFlag == "SUCCESS" ? 2:
                             inf.ExportFlag == "ERROR" ? 1:
                             inf.ExportFlag == null ? 0: 99)
               group inf by new {export, inf.StoreID, inf.DestinationDetailID,inf.PAYr } into g
               where g.Key.export == 0 
               select new { MonthCount = g.Count(), g.Key.StoreID, g.Key.PAYr, Amount = g.Sum(inf=>inf.Amount) };

By the way - please ignore some minor discrepancies you may find in naming of fields between these two - its just probably because i renamed some quickly for the sake of this question. 顺便说一句-请忽略在这两个字段之间的命名中可能会发现的一些细微差异-可能是因为为了解决这个问题,我快速重命名了一些。

看起来这就是您想要的:

where g.All(item => item.ExportFlag == "SUCCESS" || item.ExportFlag == null)

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

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