繁体   English   中英

将包含where,group by,sum和得Linq的MySQL语句转换为Sql

[英]Convert a MySQL statement containing where, group by, sum and having to Linq to Sql

我正在尝试将以下MySql转换为Linq转换为Sql(有或没有Lambda体验)

从table.column2 <'2014-11-27 00:00:00'的表中选择*,按具有sum(table.column3 = 0)> sum(table.column3 = 1)的table.column1分组

有可能吗?如果有的话吗?

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

暂无
暂无

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

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