将SUM / CASE WHEN / GROUP BY SQL查询转换为C#中的LINQ

q8l4jmvw  于 2022-12-06  发布在  C#
关注(0)|答案(1)|浏览(179)

我有一个表,其中包含一些值。我希望按日期月份分组,我的日期字段名称是ApplicationDate,以及一些枚举值。
下面是一个SQL查询,我需要将它转换为Linq:

SELECT 
    Count(he.ApplicationDate) AS Total,
    MAX(he.ApplicationDate) AS ApplicationDate,
    SUM(CASE WHEN he.Status=0 then 1 else 0 end )AS Last12MonthTotalPending,
    SUM(CASE WHEN he.Status = 1 THEN 1 ELSE 0 END )AS Last12MonthTotalApproved,
    SUM(CASE WHEN he.Status = 2 THEN 1 ELSE 0 END )AS Last12MonthTotalDenied
FROM dbo.Client_Heatings he
WHERE he.ApplicationDate >= DATEADD(Year,-1,GETDATE()) AND he.ApplicationDate <= GETDATE()
GROUP BY CAST(ApplicationDate AS DATE)

这是我的LINQ。那是我的错误LINQ。

var result = heatingList
                  .Where(r => r.Id == 123)
                  .GroupBy(r =>r.ApplicationDate )
                  .Select(grp => new HeatingApplicationSummaryDTO
                  {
                      Last12MonthTotalPending = grp.Sum( t => t.Status == 0 ? 1 : 0),
                      Last12MonthTotalApproved = grp.Sum( t => t.Status == 1 ? 1 : 0),
                      Last12MonthTotalDenied = grp.Sum( t => t.Status == 2 ? 1 : 0),
                      Total = grp.Sum(c => c.Status)
                  }).ToList();

我无法将SQL查询转换为LINQ查询。我不知道如何使用Linq转换和实现SUM/CASE节。
先谢了

zbq4xfa0

zbq4xfa01#

请尝试下列查询:

var endDate = DateTime.Now;
var startDate = endDate.AddYears(-1);

var result = heatingList
    .Where(r => r.ApplicationDate >= startDate && r.ApplicationDate <= endtDate)
    .GroupBy(r => r.ApplicationDate.Date)
    .Select(grp => new HeatingApplicationSummaryDTO
    {
        Total = grp.Count(),
        ApplicationDate = grp.Max(t => t.ApplicationDate),
        Last12MonthTotalPending = grp.Sum(t => t.Status == 0 ? 1 : 0),
        Last12MonthTotalApproved = grp.Sum(t => t.Status == 1 ? 1 : 0),
        Last12MonthTotalDenied = grp.Sum(t => t.Status == 2 ? 1 : 0),
    }).ToList();

相关问题