最终分组前的子分组

问题描述 投票:0回答:1

我有 SQL 查询,在最终分组之前我对 4 个项目进行了分组。这是 SQL 查询:

 Select DISCIP, 
                SUM(TOTAL) as TOTAL,
                SUM(COMP) as DONE,
                SUM(REM) as REM
 from (
            select
              case when Discipline in ('ELECTRICAL','F&G','INSTRUMENTATION','TELECOM','HVAC') then 'E&I'
                   when Discipline in ('PIPING') then 'PIPING'
                   when Discipline in ('EQUIPMENT') then 'EQUIPMENT'
                   when Discipline in ('MECHANICAL COMPLETION') then 'MC'
    
                   else 'OTHERS' end as DISCIP,
          
                    Count(TagNo) as TOTAL,
                    Count(case when  Completed=1 then 1 else null end) as COMP,
                    Count(case when  (Completed!=1 or Completed is null) then 1 else null end) as REM
            
           from 
                com.WBS
                where (NA=0 or NA IS NULL)
           group by Discipline)t
    
    group by t.DISCIP

在这里,我在最终分组之前将“电气”、“F&G”、“仪器”、“电信”、“暖通空调”分组为 E&I。我不知道如何在 Linq 中做同样的事情。

结果如下:

enter image description here

c# sql-server linq
1个回答
0
投票

假设您在适当的集合中拥有表的内容,该集合恰好映射了数据库上的列,您可以执行以下操作:

.Where(w => w.NA == 0 || w.NA == null)
.GroupBy(w => new
{
    DISCIP = w.Discipline switch
    {
        "ELECTRICAL" or "F&G" or "INSTRUMENTATION" or "TELECOM" or "HVAC" => "E&I",
        "PIPING" => "PIPING",
        "EQUIPMENT" => "EQUIPMENT",
        "MECHANICAL COMPLETION" => "MC",
        _ => "OTHERS"
    }
})
.Select(g => new
{
    DISCIP = g.Key.DISCIP,
    TOTAL = g.Count(),
    COMP = g.Count(w => w.Completed == 1),
    REM = g.Count(w => w.Completed != 1 || w.Completed == null)
})
.GroupBy(g => g.DISCIP)
.Select(g => new
{
    DISCIP = g.Key,
    TOTAL = g.Sum(x => x.TOTAL),
    DONE = g.Sum(x => x.COMP),
    REM = g.Sum(x => x.REM)
})
.ToList();
  • 您在 NA 列上有过滤器,确保其为 null 或 0
  • 你有纪律小组
  • 使用 switch 语句进行内部分组(它应该仅在使用此语法的 .NET 8 中工作)
  • 外部 GroupBy
  • 具有不同类型的条件计数的选择
© www.soinside.com 2019 - 2024. All rights reserved.