【问题标题】:Transform sql query to linq with groupBy and months使用 groupBy 和月份将 sql 查询转换为 linq
【发布时间】:2021-07-25 01:48:12
【问题描述】:

我有以下查询:

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 主题:link

【问题讨论】:

    标签: c# sql linq sql-to-linq-conversion


    【解决方案1】:

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

    我认为GetAbbreviatedMonthName 不支持EF,所以我们需要在ToListAsync 之后进行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多