我正在尝试将以下MySql转换为Linq转换为Sql(无论是否具有Lambda体验)

从table.column2 sum(table.column3 = 1)

是否可以,如果可以的话,是否有指针?

Column1是一个字符串,
Column2是一个DateTime,
Column3是TinyInt(布尔)

最佳答案

IQueryable<MyType> query = // get table IQueryable from the Linq2Sql data context

var dateTime = DateTime.Parse("2014-11-27");
var result = query.Where(t => t.Column2 < dateTime)
    .GroupBy(t => t.Column1)
    // Linq doesn't have HAVING, you can just use Where(). Here, we're operating on
    // an IQueryable of IGrouping, and we're filtering based on taking sums over the groups
    .Where(g => g.Sum(t => !t.Column3 ? 1 : 0) > g.Sum(t => t.Column3 ? 1 : 0))
    // it's not clear to me what you want here. Without any Select, each full grouping will get
    // pulled into memory as an IGrouping. If instead you just want the Column1 values, you'd
    // want .Select(g => g.Key)
    .Select(...);


注意,我在这里假设您已经将Column3映射到实体类中的bool。如果改为将其作为字节,则必须执行t.Column3 == 0而不是!t.Column3

关于c# - 将包含where,分组依据,求和且必须Linq的MySQL语句转换为Sql,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27203948/

10-13 06:00