使用 groupBy 和月将 sql 查询转换为 linq

Stefan0309

我有以下查询:

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,[date]),3), ' ', 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 主题:链接

它在那里

我认为您应该按月和年分组,然后再进行格式化(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)
   ...
}

我认为GetAbbreviatedMonthNameEF支持,所以我们需要在ToListAsync.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章