LINQ - 查询结果查询(一些复杂的)

时间:2018-02-14 10:53:38

标签: c# sql .net linq subquery

从以下SQL编写LINQ需要一些帮助。 主要问题是双重分组。 我已经堆叠在第二个分组

中了
group by s.[e-year], s.[e-month]

不知道如何实施。

非常感谢。

select s.[e-year], s.[e-month], count(s.projectid) 'projects entranced',
          ---------------------------------------------
          (select count(subquery.CustomerTypeID) from
              (select count(ap.ProjectID) as 'count', c.CustomerTypeID FROM Logging_ProjectsEntrances] pe
              inner join users u on pe.userid = u.userid
              inner join Companies c on u.CompanyId = c.CompanyID
              inner join AssignedProjects up on pe.ProjectID = up.ProjectID
              inner join Projects p on up.ProjectID = p.ProjectID
              where ap.ProductID = 1 and year(pe.EntranceDate) = s.[e-year] and MONTH(pe.entrancedate) = s.[e-month] and c.CustomerTypeID = 2
              group by ap.ProjectID, c.CustomerTypeID) subquery
          group by subquery.CustomerTypeID
          )
          --------------------------------------------
  from
  (
      select YEAR(pe.EntranceDate) as 'e-year', MONTH(pe.EntranceDate) as 'e-month', up.ProjectID as 'projectid' 
      FROM Logging_ProjectsEntrances pe
      inner join AssignedProjects ap on pe.ProjectID = ap.ProjectID
      inner join Projects p on ap.ProjectID = p.ProjectID
      where ap.ProductID = 1
      group by year(pe.EntranceDate), month(pe.EntranceDate), ap.ProjectID
  ) as s
  group by s.[e-year], s.[e-month]
  order by s.[e-year] desc , s.[e-month] desc

1 个答案:

答案 0 :(得分:1)

将SQL转换为LINQ查询理解:

  1. 将FROM子选项转换为单独声明的变量。
  2. 以LINQ子句顺序翻译每个子句,将monadic运算符(DISTINCTTOP等)转换为应用于整个LINQ查询的函数。
  3. 使用表别名作为范围变量。使用列别名作为匿名类型字段名称。
  4. 对多列使用匿名类型(new { ... })。
  5. 通过使用into join_variable并从join变量后跟.DefaultIfEmpty()执行另一个来模拟左连接。
  6. 用条件运算符和空值测试替换COALESCE
  7. IN翻译为.Contains(),将NOT IN翻译为! ... Contains()
  8. SELECT *必须替换为select range_variable或者连接,一个包含所有范围变量的匿名对象。
  9. SELECT字段必须替换为select new { ... },以创建包含所有所需字段或表达式的匿名对象。
  10. 必须使用扩展方法处理正确的FULL OUTER JOIN
  11. 注意:您的SQL查询使用SQL技巧(SELECT x ... GROUP BY x)执行等效的DISTINCT,应该使用它,因为它表达意图更多清楚。

    因此,对于您的SQL查询:

    var subq = (from pe in projectsEntrances
                join ap in assignedProjects on pe.ProjectID equals ap.ProjectID
                join p in projects on ap.ProjectID equals p.ProjectID
                where ap.ProductID == 1
                select new { e_year = pe.EntranceDate.Year, e_month = pe.EntranceDate.Month, ap.ProjectID }).Distinct();
    
    var ans = from s in subq
              group s by new { s.e_year, s.e_month } into sg
              orderby sg.Key.e_year descending, sg.Key.e_month descending
              select new { sg.Key.e_year, sg.Key.e_month, ProjectsEntranced = sg.Count() };