2

大家好,我在数据表中的数据如下

SKU  Quantity  UnitPrice  LinePrice
 A     10         2         20
 A     10         2         20
 B     10         2         40

我想总结一下有重复记录的SKU,得到的结果如下

SKU  Quantity  UnitPrice  LinePrice
 A     20         2         40
 B     10         2         40

我试过这个但没有运气

var query = from row in lDTSalesOrder.AsEnumerable()
                            group row by row.Field<string>("SKU") into grp
                            orderby grp.Key
                            select new
                            {
                                Id = grp.Key,
                                Sum = grp.Sum(r => r.Field<double>("UnitPrice"))
                            };
4

1 回答 1

4

在您的示例输出中,您实际上并没有对单价求和,但听起来您想要的是这样的:

var results = 
    from row in lDTSalesOrder
    group row by row.Field<string>("SKU") into grp
    orderby grp.Key
    select new
    {
        SKU = grp.Key,
        Quantity = grp.Sum(r => r.Field<double>("Quantity")),
        UnitPrice = grp.Sum(r => r.Field<double>("UnitPrice")),
        LinePrice = grp.Sum(r => r.Field<double>("LinePrice"))
    };

这将产生:

SKU  Quantity  UnitPrice  LinePrice
 A     20         4         40
 B     10         2         40

2如果你真的想为第一个结果记录产生一个单价,那Sum不是你想要的;您将不得不使用其他一些聚合函数。Min, Max, Average, 甚至Select(...).First()会产生该结果,但是您必须更精确地定义输出中想要的内容。你也可以这样做:

var results = 
    from row in lDTSalesOrder
    group row by new { SKU = row.Field<string>("SKU"), UnitPrice = row.Field<string>("UnitPrice") } into grp
    orderby grp.Key.SKU
    select new
    {
        SKU = grp.Key.SKU,
        Quantity = grp.Sum(r => r.Field<double>("Quantity")),
        UnitPrice = grp.Key.UnitPrice,
        LinePrice = grp.Sum(r => r.Field<double>("LinePrice"))
    };

这些选项中的任何一个都将产生:

SKU  Quantity  UnitPrice  LinePrice
 A     20         2         40
 B     10         2         40
于 2013-05-11T16:22:51.850 回答