SQL to Linq选择group by中的多个列

时间:2013-12-24 08:24:14

标签: c# sql linq

我想将一个SQL语句转换为LINQ,但我在做这件事时遇到了一些问题。

sql语句是:

SELECT 
    C.[Call_Date], CC.[Company], R.Resolution, 
    COUNT_BIG(*) AS CNT,
    SUM([Duration]) AS Total
FROM 
    [Calls] C
Join 
    [CompanyCharges] CC on [Company_Charge] = [CompanyCharge] 
Join 
    [Resolutions] R on C.Call_Resolution = R.Resolution
where 
    Call_Date >= '05/29/2013' 
Group By 
    C.[Call_Date], CC.[Company], CC.[CompanyCharge], R.Resolution, R.Resolution_Order
我写了类似的东西:

var stats = from c in dbContext.Calls
    join cc in dbContext.CompanyCharges on c.Company_Charge equals cc.CompanyCharge
    join r in dbContext.Resolutions on c.Call_Resolution equals r.Resolution
    where (c.Call_Date > "05/29/2013")
    group new { c, cc, r } by new { c.Call_Date, cc.CompanyCharge, r.Resolution, r.Resolution_Order } into statsGroup
    select new { Count = statsGroup.Count(), ??? };

我设法计算元素,但我需要一个sum [duration]和来自不同表的一些列。 请与我分享你的智慧。

1 个答案:

答案 0 :(得分:4)

假设[Duration]字段是[Calls]表的一部分:

var stats = /* ... */
    select new 
    { 
        Count = statsGroup.Count(), 
        Total = statsGroup.Sum(stat => stat.c.Duration),
    };

您可能希望将分组字段包含在新的匿名类型中:

var stats = /* ... */
    select new 
    { 
        Call_Date = statsGroup.Key.c.Call_Date,
        CompanyCharge = statsGroup.Key.cc.CompanyCharge, 
        Resolution = statsGroup.Key.r.Resolution, 
        Count = statsGroup.Count(), 
        Total = statsGroup.Sum(stat => stat.c.Duration),
    };