0

我有一个查询,我需要在其中获取 Commpliance 和 NonCompliance 的计数

这是我需要将其转换为 linq 的 SQL 版本...

 select ScheduleClause,
    COUNT(case Compliance 
            when 1 then 1 end) Compliance,
    Count(case Compliance
            when 0 then 1 end) NonCompliance
 from Compliance_RiskRegisterEntry cr
 where cr.RiskRegisterTypeId = 1 and Auditor = 5508 and MONTH(AuditDate) = 10 and           YEAR(AuditDate) = 2013
group by ScheduleClause

我尝试了这个 linq 查询,但我得到了不同的结果

 compliance
     .GroupBy(x => new
     {
       x.ScheduleClause, x.Compliance
     })
     .Where(x => x.Key.Compliance == 1)
     .Select(x => new RiskRegisterCompliancePerCategoryDto
         {
             ScheduleClause =  x.Key.ScheduleClause,
             Compliant = x.Key.Compliance == 1 ? 1 : 0,
             NonCompliant = x.Key.Compliance == 0 ? 1 : 0,
             GrandTotal = x.Count()
          }).ToList();
4

2 回答 2

0
    compliance
         .Where(p=> p.RiskRegisterTypeId = 1 && p.Auditor = 5508 && 
                    SqlFunctions.DatePart("MM", p.AuditDate) = 10 &&
                    SqlFunctions.DatePart("yy", p.AuditDate) = 2013)
         .GroupBy(x => x.ScheduleClause)
         .Select(x => new RiskRegisterCompliancePerCategoryDto
             {
                 ScheduleClause =  x.Key.ScheduleClause,
                 Compliant = x.Key.Compliance == 1 ? 1 : 0,
                 NonCompliant = x.Key.Compliance == 0 ? 1 : 0,
                 GrandTotal = x.Count()
              }).ToList();
于 2013-10-20T15:33:51.913 回答
0

这取决于您的确切列定义。我在这里使用

Create Table Compliance_RiskRegisterEntry (
    ScheduleClause varchar(10),
    AuditDate datetime not null,
    RiskRegisterTypeID int not null,
    Auditor Int,
    Compliance bit not null
);

有了这个,以下 Linq 工作:

compliance
    .Where(p => p.RiskRegisterTypeID == 1 && 
                p.Auditor == 5508 && 
                p.AuditDate.Month == 10 &&
                p.AuditDate.Year == 2013
    )
    .GroupBy(x => x.ScheduleClause)
    .Select(x => new {
        ScheduleClause = x.Key,
        Compliant = x.Sum(y => y.Compliance ? 1 : 0),
        NonCompliant = x.Sum(y => y.Compliance ? 0 : 1),
        GrandTotal = x.Count()
    });

而不是x.Sum(...)你可以使用x.Count(y.Compliance),但是为此生成的查询看起来比使用 Sum 更糟糕

于 2013-10-20T16:05:31.070 回答