Skip to content

Commit

Permalink
- 优化 GroupBy 聚合函数 Count(bool) 解析成 sum(case when);dotnetcore#1841
Browse files Browse the repository at this point in the history
  • Loading branch information
2881099 committed Jul 2, 2024
1 parent a5d7595 commit 36af40a
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 111 deletions.
13 changes: 12 additions & 1 deletion Examples/base_entity/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -619,7 +619,18 @@ static void Main(string[] args)
BaseEntity.Initialization(fsql, () => _asyncUow.Value);
#endregion



var sqlc001 = fsql.Select<User1>()
.GroupBy(a => a.GroupId)
.ToSql(g => new
{
cou1 = g.Count(),
cou2 = g.Count(g.Value.Nickname),
cou3 = g.Count(g.Value.Nickname == "xx"),
cou4 = g.Count(g.Value.Sort > 50),
cou5 = g.Count(g.Value.Sort > 50 || g.Value.Username == "xx"),
});

fsql.Select<Account>().As("aaa").Where(p => p.ID == 1).AsQueryable().Distinct().Select(p => new { p.Name, p.ID }).Count();


Expand Down
109 changes: 0 additions & 109 deletions FreeSql/FreeSql.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion FreeSql/Internal/CommonExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1194,7 +1194,10 @@ public string ExpressionLambdaToSql(Expression exp, ExpTSC tsc)
{
switch (exp3.Method.Name)
{
case "Count": return exp3.Arguments.Count == 0 ? "count(1)" : $"count({ExpressionLambdaToSql(exp3.Arguments[0], tsc)})";
case "Count":
if (exp3.Arguments.Count == 0) return "count(1)";
if (exp3.Arguments[0].Type == typeof(bool)) return $"sum({_common.IIF(ExpressionLambdaToSql(exp3.Arguments[0], tsc), "1", "0")})";
return $"count({ExpressionLambdaToSql(exp3.Arguments[0], tsc)})";
case "Sum": return $"sum({ExpressionLambdaToSql(exp3.Arguments[0], tsc)})";
case "Avg": return $"avg({ExpressionLambdaToSql(exp3.Arguments[0], tsc)})";
case "Max": return $"max({ExpressionLambdaToSql(exp3.Arguments[0], tsc)})";
Expand Down

0 comments on commit 36af40a

Please sign in to comment.