Wednesday, 18 December 2013

Inner join with Group by and case statement in Linq to sql


I have the following sql below which I am having real trouble getting into a LINQ statement. 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. Various reasons why i needed to do this but I cant seem to reproduce it in LINQ.
Here is the sql Query
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
Convert This query in Linq to Sql
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) };

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.

No comments:

Post a Comment