-
看了文档,使用FreeSql目前很容易生成以下SQL(SqlServer): select count(*), count(city_name), count(distinct city_name) from tb_county; 但是,如何生成以下SQL: select
sex ,
count (case when student.Province = '广东省' then 1 end )as 广东省 ,
count (case when student.Province = '江西省' then 1 end )as 江西省 ,
count (case when student.Province = '浙江省' then 1 end )as 浙江省
from student
group by sex
在EF Core中,该SQL很容易生成: var query = context.Student
.GroupBy(p => p.Sex)
.Select(g => new { Sex = g.Key, Count1 = g.Where(s => s.Province="广东省").Count() }); 不知FreeSql当前是否能够实现该需求?如果可以的话,希望在“分组查询”章节进一步完善文档,谢谢! |
Beta Was this translation helpful? Give feedback.
Answered by
2881099
Jan 10, 2023
Replies: 3 comments 5 replies
-
尝试了不少时间,发现这样子写可以实现: var data = await FreeSql.Select<Student>()
.GroupBy(s => s.Sex)
.ToDictionaryAsync(g => new { Total = g.Count(), Guangdong = g.Count(SqlExt.Case().When(g.Value.Province == "广东省", 1).End()) }); 而这样写则异常: var data = await FreeSql.Select<Student>()
.GroupBy(s => s.Sex)
.ToDictionaryAsync(g => new { Total = g.Count(), Guangdong = SqlExt.Count(SqlExt.Case().When(g.Value.Province == "广东省", 1).End()) }); 这样写结果是不对的: var data = await FreeSql.Select<Student>()
.GroupBy(s => s.Sex)
.ToDictionaryAsync(g => new { Total = g.Count(), Guangdong = g.Count(g.Value.Province == "广东省" ? 1 : 0) }); |
Beta Was this translation helpful? Give feedback.
0 replies
-
不要用 COUNT,用 SUM,这其实是 SQL 知识体系啊。 g.Sum(g.Value.Province == "广东省" ? 1 : 0) 对应 SUM(case when province = '广东省' then 1 else 0) |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
LeaFrock
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
不要用 COUNT,用 SUM,这其实是 SQL 知识体系啊。
g.Sum(g.Value.Province == "广东省" ? 1 : 0) 对应
SUM(case when province = '广东省' then 1 else 0)