2016-11-14 82 views
0

你能幫我這個MySQL翻譯成Linq的請:LINQ Case語句與COUNT和GROUP

SELECT distcode, COUNT(cid) as count_all_case 
,count(case when labid = 1 then cid end) as count_id1 
,count(case when labid = 2 then cid end) as count_id2 
,count(case when labid = 3 then cid end) as count_id3 
FROM labcase 
WHERE SEQ is not NULL AND date_serv BETWEEN 20160101 AND 20161001 
GROUP BY distcode 

感謝

回答

3

好吧,你需要查看生成的SQL,但過濾和分組部分很簡單 - 只有計數位纔是特別棘手的。你也許可以做到這組投影的範圍內:

var start = new DateTime(2016, 1, 1); 
var end = new DateTime(2016, 10, 1); 
var query = from labCase in db.LabCase 
      where labCase.Seq != null && 
       labCase.DateServ >= start && 
       labCase.DateServ <= end 
      group labCase by labCase.DistCode into g 
      select new 
      { 
       DistCode = g.Key, 
       CountId1 = g.Count(x => x.LabId == 1), 
       CountId2 = g.Count(x => x.LabId == 2), 
       CountId3 = g.Count(x => x.LabId == 3) 
      }; 
+0

應該在where子句不labCase.date_serv日期條款?最有可能只是一個錯字 –

+1

@Ctrl_Alt_Defeat:是的,固定的。 –

0

這裏是拉姆達查詢

var query = db.labcase 
     .Where(p => p.SEQ != null && p.date_serv >= new Datetime(2016,01,01) && p.date_serv <= new Datetime(2016,01,10)) 
     .GroupBy(f => new {distcode} 
       , (key , elem) => new { 
    key.distcode 
    ,count_id1 = elem.Count(x => x.LabId == 1) 
    ,count_id2 = elem.Count(x => x.LabId == 2) 
    ,count_id3 = elem.Count(x => x.LabId == 3) 
})