使用LINQ to SQL实现GROUP BY WITH ROLLUP

11

我正在尝试将一些旧的SQL代码改写成LINQ to SQL。我有一个带有GROUP BY WITH ROLLUP的存储过程,但我不确定它的LINQ等效语句是什么。LINQ有一个GroupBy方法,但似乎不支持ROLLUP。

一个简化的示例结果如下:

+-----------+---------------+--------------------+
|   城市     |  服务计划    |     客户数量      |
+-----------+---------------+--------------------+
| 西雅图     |  计划A       |                  10 |
| 西雅图     |  计划B       |                   5 |
| 西雅图     |  所有         |                  15 |
| 波特兰   |  计划A       |                  20 |
| 波特兰   |  计划C       |                  10 |
| 波特兰   |  所有         |                  30 |
| 所有       |  所有         |                  45 |
+-----------+---------------+--------------------+

你有任何想法如何使用LINQ to SQL获得这些结果吗?

4个回答

15

我找到了一个更简单的解决方案。我试图使它比必要的复杂度要高得多。与其需要3-5个类/方法,我只需要一个方法。

基本上,你自己进行排序和分组,然后调用 WithRollup() 来获取一个带有子总计和总计的 List<>。我无法弄清楚如何在 SQL 端生成子总计和总计,所以这些是使用 LINQ to Objects 完成的。以下是代码:

/// <summary>
/// Adds sub-totals to a list of items, along with a grand total for the whole list.
/// </summary>
/// <param name="elements">Group and/or sort this yourself before calling WithRollup.</param>
/// <param name="primaryKeyOfElement">Given a TElement, return the property that you want sub-totals for.</param>
/// <param name="calculateSubTotalElement">Given a group of elements, return a TElement that represents the sub-total.</param>
/// <param name="grandTotalElement">A TElement that represents the grand total.</param>
public static List<TElement> WithRollup<TElement, TKey>(this IEnumerable<TElement> elements,
    Func<TElement, TKey> primaryKeyOfElement,
    Func<IGrouping<TKey, TElement>, TElement> calculateSubTotalElement,
    TElement grandTotalElement)
{
    // Create a new list the items, subtotals, and the grand total.
    List<TElement> results = new List<TElement>();
    var lookup = elements.ToLookup(primaryKeyOfElement);
    foreach (var group in lookup)
    {
        // Add items in the current group
        results.AddRange(group);
        // Add subTotal for current group
        results.Add(calculateSubTotalElement(group));
    }
    // Add grand total
    results.Add(grandTotalElement);

    return results;
}

以下是如何使用它的示例:

class Program
{
    static void Main(string[] args)
    {
        IQueryable<CustomObject> dataItems = (new[]
        {
            new CustomObject { City = "Seattle", Plan = "Plan B", Charges = 20 },
            new CustomObject { City = "Seattle", Plan = "Plan A", Charges = 10 },
            new CustomObject { City = "Seattle", Plan = "Plan B", Charges = 20 },
            new CustomObject { City = "Seattle", Plan = "Plan A", Charges = 10 },
            new CustomObject { City = "Seattle", Plan = "Plan A", Charges = 10 },
            new CustomObject { City = "Seattle", Plan = "Plan A", Charges = 10 },
            new CustomObject { City = "Portland", Plan = "Plan A", Charges = 10 },
            new CustomObject { City = "Portland", Plan = "Plan A", Charges = 10 },
            new CustomObject { City = "Portland", Plan = "Plan C", Charges = 30 },
            new CustomObject { City = "Portland", Plan = "Plan C", Charges = 30 },
            new CustomObject { City = "Portland", Plan = "Plan C", Charges = 30 }
        }).AsQueryable();

        IQueryable<CustomObject> orderedElements = from item in dataItems
                                                   orderby item.City, item.Plan
                                                   group item by new { item.City, item.Plan } into grouping
                                                   select new CustomObject
                                                   {
                                                       City = grouping.Key.City,
                                                       Plan = grouping.Key.Plan,
                                                       Charges = grouping.Sum(item => item.Charges),
                                                       Count = grouping.Count()
                                                   };

        List<CustomObject> results = orderedElements.WithRollup(
            item => item.City,
            group => new CustomObject
            {
                City = group.Key,
                Plan = "All",
                Charges = group.Sum(item => item.Charges),
                Count = group.Sum(item => item.Count)
            },
            new CustomObject
            {
                City = "All",
                Plan = "All",
                Charges = orderedElements.Sum(item => item.Charges),
                Count = orderedElements.Sum(item => item.Count)
            });

        foreach (var result in results)
            Console.WriteLine(result);

        Console.Read();
    }
}

class CustomObject
{
    public string City { get; set; }
    public string Plan { get; set; }
    public int Count { get; set; }
    public decimal Charges { get; set; }

    public override string ToString()
    {
        return String.Format("{0} - {1} ({2} - {3})", City, Plan, Count, Charges);
    }
}

4
我明白了!这是一个通用的GroupByWithRollup,它只按两个列进行分组,但可以轻松扩展以支持更多。我可能会有另一个版本,可以接受三个列。关键类/方法是Grouping<>, GroupByMany<>()和GroupByWithRollup<>()。SubTotal()和GrandTotal()方法是在实际使用GroupByWithRollup<>()时的帮助程序。以下是代码,后跟如何使用它的示例。
/// <summary>
/// Represents an instance of an IGrouping<>.  Used by GroupByMany(), GroupByWithRollup(), and GrandTotal().
/// </summary>
public class Grouping<TKey, TElement> : IGrouping<TKey, TElement>
{
    public TKey Key { get; set; }
    public IEnumerable<TElement> Items { get; set; }

    public IEnumerator<TElement> GetEnumerator()
    {
        return Items.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return Items.GetEnumerator();
    }
}

public static class Extensions
{
    /// <summary>
    /// Groups by two columns.
    /// </summary>
    /// <typeparam name="TElement">Type of elements to group.</typeparam>
    /// <typeparam name="TKey1">Type of the first expression to group by.</typeparam>
    /// <typeparam name="TKey2">Type of the second expression to group by.</typeparam>
    /// <param name="orderedElements">Elements to group.</param>
    /// <param name="groupByKey1Expression">The first expression to group by.</param>
    /// <param name="groupByKey2Expression">The second expression to group by.</param>
    /// <param name="newElementExpression">An expression that returns a new TElement.</param>
    public static IQueryable<Grouping<TKey1, TElement>> GroupByMany<TElement, TKey1, TKey2>(this IOrderedQueryable<TElement> orderedElements,
        Func<TElement, TKey1> groupByKey1Expression,
        Func<TElement, TKey2> groupByKey2Expression,
        Func<IGrouping<TKey1, TElement>, IGrouping<TKey2, TElement>, TElement> newElementExpression
        )
    {
        // Group the items by Key1 and Key2
        return from element in orderedElements
               group element by groupByKey1Expression(element) into groupByKey1
               select new Grouping<TKey1, TElement>
               {
                   Key = groupByKey1.Key,
                   Items = from key1Item in groupByKey1
                           group key1Item by groupByKey2Expression(key1Item) into groupByKey2
                           select newElementExpression(groupByKey1, groupByKey2)
               };
    }

    /// <summary>
    /// Returns a List of TElement containing all elements of orderedElements as well as subTotals and a grand total.
    /// </summary>
    /// <typeparam name="TElement">Type of elements to group.</typeparam>
    /// <typeparam name="TKey1">Type of the first expression to group by.</typeparam>
    /// <typeparam name="TKey2">Type of the second expression to group by.</typeparam>
    /// <param name="orderedElements">Elements to group.</param>
    /// <param name="groupByKey1Expression">The first expression to group by.</param>
    /// <param name="groupByKey2Expression">The second expression to group by.</param>
    /// <param name="newElementExpression">An expression that returns a new TElement.</param>
    /// <param name="subTotalExpression">An expression that returns a new TElement that represents a subTotal.</param>
    /// <param name="totalExpression">An expression that returns a new TElement that represents a grand total.</param>
    public static List<TElement> GroupByWithRollup<TElement, TKey1, TKey2>(this IOrderedQueryable<TElement> orderedElements,
        Func<TElement, TKey1> groupByKey1Expression,
        Func<TElement, TKey2> groupByKey2Expression,
        Func<IGrouping<TKey1, TElement>, IGrouping<TKey2, TElement>, TElement> newElementExpression,
        Func<IGrouping<TKey1, TElement>, TElement> subTotalExpression,
        Func<IQueryable<Grouping<TKey1, TElement>>, TElement> totalExpression
        )
    {
        // Group the items by Key1 and Key2
        IQueryable<Grouping<TKey1, TElement>> groupedItems = orderedElements.GroupByMany(groupByKey1Expression, groupByKey2Expression, newElementExpression);

        // Create a new list the items, subtotals, and the grand total.
        List<TElement> results = new List<TElement>();
        foreach (Grouping<TKey1, TElement> item in groupedItems)
        {
            // Add items under current group
            results.AddRange(item);
            // Add subTotal for current group
            results.Add(subTotalExpression(item));
        }
        // Add grand total
        results.Add(totalExpression(groupedItems));

        return results;
    }

    /// <summary>
    /// Returns the subTotal sum of sumExpression.
    /// </summary>
    /// <param name="sumExpression">An expression that returns the value to sum.</param>
    public static int SubTotal<TKey, TElement>(this IGrouping<TKey, TElement> query, Func<TElement, int> sumExpression)
    {
        return query.Sum(group => sumExpression(group));
    }

    /// <summary>
    /// Returns the subTotal sum of sumExpression.
    /// </summary>
    /// <param name="sumExpression">An expression that returns the value to sum.</param>
    public static decimal SubTotal<TKey, TElement>(this IGrouping<TKey, TElement> query, Func<TElement, decimal> sumExpression)
    {
        return query.Sum(group => sumExpression(group));
    }

    /// <summary>
    /// Returns the grand total sum of sumExpression.
    /// </summary>
    /// <param name="sumExpression">An expression that returns the value to sum.</param>
    public static int GrandTotal<TKey, TElement>(this IQueryable<Grouping<TKey, TElement>> query, Func<TElement, int> sumExpression)
    {
        return query.Sum(group => group.Sum(innerGroup => sumExpression(innerGroup)));
    }

    /// <summary>
    /// Returns the grand total sum of sumExpression.
    /// </summary>
    /// <param name="sumExpression">An expression that returns the value to sum.</param>
    public static decimal GrandTotal<TKey, TElement>(this IQueryable<Grouping<TKey, TElement>> query, Func<TElement, decimal> sumExpression)
    {
        return query.Sum(group => group.Sum(innerGroup => sumExpression(innerGroup)));
    }

以下是使用它的示例:

class Program
{
    static void Main(string[] args)
    {
        IQueryable<CustomObject> dataItems = (new[]
        {
            new CustomObject { City = "Seattle", Plan = "Plan B", Charges = 20 },
            new CustomObject { City = "Seattle", Plan = "Plan A", Charges = 10 },
            new CustomObject { City = "Seattle", Plan = "Plan B", Charges = 20 },
            new CustomObject { City = "Seattle", Plan = "Plan A", Charges = 10 },
            new CustomObject { City = "Seattle", Plan = "Plan A", Charges = 10 },
            new CustomObject { City = "Seattle", Plan = "Plan A", Charges = 10 },
            new CustomObject { City = "Portland", Plan = "Plan A", Charges = 10 },
            new CustomObject { City = "Portland", Plan = "Plan A", Charges = 10 },
            new CustomObject { City = "Portland", Plan = "Plan C", Charges = 30 },
            new CustomObject { City = "Portland", Plan = "Plan C", Charges = 30 },
            new CustomObject { City = "Portland", Plan = "Plan C", Charges = 30 }
        }).AsQueryable();

        List<CustomObject> results = dataItems.OrderBy(item => item.City).ThenBy(item => item.Plan).GroupByWithRollup(
            item => item.City,
            item => item.Plan,
            (primaryGrouping, secondaryGrouping) => new CustomObject
            {
                City = primaryGrouping.Key,
                Plan = secondaryGrouping.Key,
                Count = secondaryGrouping.Count(),
                Charges = secondaryGrouping.Sum(item => item.Charges)
            },
            item => new CustomObject
            {
                City = item.Key,
                Plan = "All",
                Count = item.SubTotal(subItem => subItem.Count),
                Charges = item.SubTotal(subItem => subItem.Charges)
            },
            items => new CustomObject
            {
                City = "All",
                Plan = "All",
                Count = items.GrandTotal(subItem => subItem.Count),
                Charges = items.GrandTotal(subItem => subItem.Charges)
            }
            );
        foreach (var result in results)
            Console.WriteLine(result);

        Console.Read();
    }
}

class CustomObject
{
    public string City { get; set; }
    public string Plan { get; set; }
    public int Count { get; set; }
    public decimal Charges { get; set; }

    public override string ToString()
    {
        return String.Format("{0} - {1} ({2} - {3})", City, Plan, Count, Charges);
    }
}

哎呀,还有些错误。当我对实际的SQL数据运行它时,它会抛出异常,因为我需要使用Expression<Func<>>而不是只有Func<>。我也不能在表达式中使用"from x in y"语法。这篇文章对此有所帮助:http://www.richardbushnell.net/index.php/2008/01/16/using-lambda-expressions-with-linq-to-sql/。所以我仍然需要清理一下代码。 - Ecyrb
这种方法证明比必要的复杂得多。我无法使分组完全在SQL端工作。最后,我放弃了这种方法,并提出了更简单的接受解决方案。 - Ecyrb

2

@Ecyrb,五年后的你好!

对于LINQ to SQL,我只是比普通的LINQ(针对对象)略有了解。但是,由于您在标签中除了“LINQ-2-SQL”标签外还有一个“LINQ”标签,因为您似乎主要关心结果(而不是向数据库注册更改),并且这是我通过谷歌搜索寻找SQL Server的“Rollup”分组函数的LINQ等效项时找到的唯一相关资源,因此我将为今天任何有类似需求的人提供自己的替代解决方案。

基本上,我的方法是创建一个“.GroupBy().ThenBy()”链式语法,类似于“.OrderBy().ThenBy()”语法。我的扩展期望以IGrouping对象集合——即运行“.GroupBy()”时得到的结果——作为其源。然后,它将收集数据并取消分组以返回原始对象,最后根据新的分组函数重新对数据进行分组,生成另一组IGrouping对象,并将新分组的对象添加到源对象集合中。

public static class mySampleExtensions {

    public static IEnumerable<IGrouping<TKey, TSource>> ThenBy<TSource, TKey> (     
        this IEnumerable<IGrouping<TKey, TSource>> source,
        Func<TSource, TKey> keySelector) {

        var unGroup = source.SelectMany(sm=> sm).Distinct(); // thank you flq at https://dev59.com/RHRB5IYBdhLWcg3w7rmV
        var reGroup = unGroup.GroupBy(keySelector);

        return source.Concat(reGroup);}

}

您可以使用方法,在“.ThenBy()”函数的适当区域放置常量值,以匹配SQL Server的Rollup逻辑。我更喜欢使用null值,因为它是最灵活的强制转换常量。强制转换很重要,因为您在.GroupBy()和.ThenBy()中使用的函数必须导致相同的对象类型。使用您在2009年8月31日第一次响应中创建的“dataItems”变量,代码如下:

var rollItUp = dataItems
    .GroupBy(g=> new {g.City, g.Plan})
        .ThenBy(g=> new {g.City, Plan = (string) null})
        .ThenBy(g=> new {City = (string) null, Plan = (string) null})
    .Select(s=> new CustomObject {
        City = s.Key.City, 
        Plan = s.Key.Plan, 
        Count = s.Count(),
        Charges = s.Sum(a=> a.Charges)})
    .OrderBy(o=> o.City) // This line optional
        .ThenBy(o=> o.Plan); // This line optional

如果需要,您可以将".ThenBy()"逻辑中的null替换为"all"。

通过使用".ThenBy()",您可以模拟SQL Server的分组集和立方体。此外,对我而言,".ThenBy()"运行良好,我没有预见到与".OrderBy()"方法中的".ThenBy()"名称等效的任何问题,但如果有问题,您可能需要考虑将其命名为".ThenGroupBy()"以区分。

正如提到的那样,我不使用Linq-to-SQL,但我使用F#的类型提供程序系统,我了解在许多方面下它使用Linq-to-SQL。因此,我尝试了我的扩展,针对来自我的F#项目的这种对象,它按照我的预期工作。尽管我绝对不知道这是否意味着在这方面有任何有趣的东西。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接