将包含 where、group by、sum 和必须的 MySQL 语句转换为 Linq to Sql

Posted

技术标签:

【中文标题】将包含 where、group by、sum 和必须的 MySQL 语句转换为 Linq to Sql【英文标题】:Convert a MySQL statement containing where, group by, sum and having to Linq to Sql 【发布时间】:2014-11-29 15:39:04 【问题描述】:

我正在尝试将以下 mysql 转换为 Linq 到 Sql(有或没有 Lambda 表达式)

select * from table where table.column2 sum(table.column3 = 1)

有可能吗?如果有的话,有什么建议吗?

Column1 是一个字符串, Column2 是一个日期时间, Column3 是 TinyInt(布尔值)

【问题讨论】:

【参考方案1】:
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 映射到实体类中的布尔值。如果您将它作为一个字节,那么您将不得不使用t.Column3 == 0 而不是!t.Column3

【讨论】:

Column3 是实体中的一个枚举器,它正在阻止上述工作 @HarryParker 数据库中的Column3是什么类型?您可以将您的数据库表架构和 Linq2Sql 实体类添加到您的帖子中吗?

以上是关于将包含 where、group by、sum 和必须的 MySQL 语句转换为 Linq to Sql的主要内容,如果未能解决你的问题,请参考以下文章

group by having where order by

不能在 Group by/Order by/Where/ON 子句中使用 Group 或 Aggregate 函数(min()、max()、sum()、count()、...等)

怎么使用group by?

GROUP BY,WHERE,HAVING之间的区别和用法

SQL中where和group by可以连用吗?having算是对检索条件的补充吗?

GROUP BY,WHERE,HAVING之间的区别和用法