如何解决使用 groupBy 和月将 sql 查询转换为 linq
select concat(Left(DateName(month,[date]),3),' ',Year([date])),sum(TotalAttendants) as Total,Sum(FemaleAttendants) as Women,Sum(MaleAttendants) as Men
from dbo.Events
where IsDeleted=0 and EventTypeId = 1
group by concat(Left(DateName(month,Year([date]))
并且我想将其转换为 c# linq lambda 表达式。
我尝试过这样的事情:
var response = await _context.Events
.Where(x => !x.IsDeleted && x.EventTypeId == Domain.Enums.EventTypes.DirectBeneficiaries)
.GroupBy(x => x.Date)
.Select(x => new EventViewData
{
MaleAttendants = x.Sum(u => u.MaleAttendants),FemaleAttendants = x.Sum(u => u.FemaleAttendants),TotalAttendants = x.Sum(u => u.TotalAttendants),MonthName = x.Key.ToString("00")
}).ToListAsync();
我得到的结果与我在 mssql 管理工作室得到的结果不同。
如果您需要更多关于数据结构和表事件的信息,这里是我的另一个 stackoverflow 主题:link
解决方法
我认为您应该按月和年分组,并在稍后(如果需要)进行格式化(concat 等)。
select
...
from dbo.Events
..
group by Month([date]),Year([date]))
然后在 linq 中你可以:
...
.GroupBy(x => new { Year = x.Date.Year,Month = x.Date.Month } )
.Select(x => new // Note no type name
{
MaleAttendants = x.Sum(u => u.MaleAttendants),FemaleAttendants = x.Sum(u => u.FemaleAttendants),TotalAttendants = x.Sum(u => u.TotalAttendants),Month = x.Key.Month,Year = x.Key.Year
})
.ToListAsync() // Hit the db
.Select( x => new EventViewData
{
x.MaleAttendants
x.FemaleAttendants
x.TotalAttendants
MonthName = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(x.Month)
...
}
我认为 EF 不支持 GetAbbreviatedMonthName
,因此我们需要在 ToListAsync
之后进行。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。