从SQL到LINQ-多个分组依据语句和一个联接

时间:2018-11-13 16:15:44

标签: c# sql linq entity

正在开发LINQ查询以返回与此SQL查询相同的结果:

SELECT 
  x.departmentid, 
  Count(x.transactionid) 
FROM 
  (
    SELECT 
      t.id AS transactionid, 
      tp.departmentid AS departmentid 
    FROM 
      history.transactions t 
      JOIN history.transactionproducts tp ON t.id = tp.transactionid 
    GROUP BY 
      t.id, 
      tp.departmentid
  ) AS x 
GROUP BY 
  x.departmentid

我正在努力弄清楚如何在LINQ中多次按部门编号分组。

这是到目前为止我尝试过的:

var deptTransactionsCount = from transaction in transactions
                                        join product in transactionProducts on transaction.Id equals product.TransactionId
                                        group transaction by new { product.TransactionId, product.DepartmentId }
                                        into groupedbyTransAndDept
                                        select new
                                                   {
                                                       DepartmentID = groupedbyTransAndDept.Key.DepartmentId,
                                                       TotalTransactionsCount = groupedbyTransAndDept.Count()
                                                   };

同样,我不确定如何解释多重分组依据语句。

以下是SQL查询的结果: results

3 个答案:

答案 0 :(得分:0)

我认为我们可以简化它。

length message length

答案 1 :(得分:0)

根据我的经验,很难与Linq进行分组和联接,您可以在数据库中创建视图并使用它。

答案 2 :(得分:0)

您无需采取任何特殊措施即可处理多个分组。您有一个派生表,它是一个分组。那是一个查询。由此,您可以进行另一个分组。那是另一个查询。

var deptTransactionsCount = (
    from dept in (
        from t in transactions
        join tp in transactionProducts on t.Id equals tp.TransactionId
        group tp by new { tp.TransactionId, tp.DepartmentId } into groupedbyTransAndDept
        from transAndDept in groupedbyTransAndDept
        select new
        {
            transAndDept.TransactionId,
            transAndDept.DepartmentId
        })
    group dept by dept.DepartmentId into groupedByDept
    select new
    {
        DepartmentId = groupedByDept.Key,
        Count = groupedByDept.Count()
    }).ToList();

由于它是LINQ,因此您可以排除内部查询,如果这样可以更轻松地了解其作用。

var innerQuery =
    from t in transactions
    join tp in transactionProducts on t.Id equals tp.TransactionId
    group tp by new { tp.TransactionId, tp.DepartmentId } into groupedbyTransAndDept
    from transAndDept in groupedbyTransAndDept
    select new
    {
        transAndDept.TransactionId,
        transAndDept.DepartmentId
    };

var deptTransactionsCount = (
    from dept in innerQuery
    group dept by dept.DepartmentId into groupedByDept
    select new
    {
        DepartmentId = groupedByDept.Key,
        Count = groupedByDept.Count()
    }).ToList();