开发者

LINQ Case statement within Count

开发者 https://www.devze.com 2023-04-06 16:55 出处:网络
Can you help me translate this sql into Linq please: select count(case when t.TypeID = 1 then t.TypeID end) as 开发者_如何学Pythona,

Can you help me translate this sql into Linq please:

select 
    count(case when t.TypeID = 1 then t.TypeID end) as 开发者_如何学Pythona,
    count(case when t.TypeID = 2 then t.TypeID end) as b,
    count(case when t.TypeID = 3 then t.TypeID end) as c
from myTable t

I've searched the internet and found some similar sql but nothing that fits this scenario. Is it possible?

Thanks


I think you want something like this

var query = new
            {
              a = (context.MyTable.Where(t => t.TypeID == 1).Count(),
              b = (context.MyTable.Where(t => t.TypeID == 2).Count(),
              c = (context.MyTable.Where(t => t.TypeID == 3).Count(),
            }

Edit - If you want it all in one query you could do this:

var query = from x in context.MyTable
            group x by 1 into xg
            select new
            {
              a = xg.Where(t => t.TypeID == 1).Count(),
              b = xg.Where(t => t.TypeID == 2).Count(),
              c = xg.Where(t => t.TypeID == 3).Count(),
            };
0

精彩评论

暂无评论...
验证码 换一张
取 消