【问题标题】:Is it possible to select the sum of a column, grouping by another column?是否可以选择一列的总和,按另一列分组?
【发布时间】:2012-07-02 13:06:49
【问题描述】:

表格格式:

Date   |   NumberIWantToSum   |   ID(PK)   |   ForeignKeyID

对于给定的 ForeignKeyID,我想使用 Linq2SQL 对具有相同日期的所有 NumberIWantToSum 值求和,然后使用行中的所有值填充我自己的自定义类的列表。

这可能吗?

所以,给定值:

    Date   |   NumberIWantToSum   |   ID(PK)   |   ForeignKeyID
   1/1/1             1                  123              2
   1/1/1             12                 124              2
   1/1/1             44                 125              3
   1/1/2             14                 126              2

我得到了这个方法的 ForeignKeyID 参数,假设它是 2,所以这个方法应该返回行:

   1/1/1             13                 123              2
   1/1/2             14                 126              2

我尝试这样做:

(from o in context.table.Where(r => r.GroupByThisColID == GroupByThisColID)
 select new CustomClass()
 {
     ID = o.ID,
     Date = o.Date,
     NumberIWantToSum = o.NumberIWantToSum,
     ForeignKeyID  = o.ForeignKeyID
 }).ToList();

但是,这不会对 NumberIWantToSum 的值求和并将它们合并为一行。

我该怎么做呢?

【问题讨论】:

  • ID 字段 - 它包含在预期结果中,但不包含在 group by(或 MIN/MAX/etc)中。那么它怎么知道选择 123 而不是 124 呢?那里缺少什么...?
  • 也许我遗漏了一些东西,但不应该与 2 组合产生 1+12+14 吗?
  • 我也不确定如何处理;为该列返回哪个无关紧要(因为两者都是唯一的)。有关如何处理此问题的任何建议?
  • @JustinPihony - 不,因为 44 的 GroupByThisColID 为 3,而其余的有 2。我只希望返回 GroupByThisColID 为 2 的值(或传入的任何参数)。
  • 我不是 LINQ 专家,但在 TSQL 中,您的 2 是 WHERE 参数,而 DATE 是 Group By 列。但是,您必须告诉它如何处理 ID 字段,否则它将为此处的每个唯一值返回一行,因此不会对任何内容求和。

标签: c# .net linq linq-to-sql sum


【解决方案1】:

根据您的解释,GroupByThisColdID 用于过滤,而不是分组。您实际上想按日期分组。

试试这个:

var query = from o in context.table
            where o.GroupByThisColID == GroupByThisColID
            group o by o.Date into grouping
            select new CustomClass()
            {
                ID = grouping.First().ID,
                Date = grouping.Key,
                SummedNumbers = grouping.Sum(g => g.NumberIWantToSum),
                GroupByThisColID  = grouping.First().GroupByThisColID
            };

使用grouping.First().ID 将返回第一个 ID,尽管它们可能不同。在您的示例数据中,这将是“123”。

【讨论】:

    【解决方案2】:
    var r = from x in table
            group x by x.GroupByThisColID into g
            select new
            {
                Key = g.Key,
                Sum = g.Sum(i => i.NumberIWantToSum)
            };
    
    foreach (var x in r)
    {
        var key = x.Key;
        var sum = x.Sum;
    }
    

    【讨论】:

      【解决方案3】:
      var results = context.table.GroupBy( t=> t.GroupByThisColID)
          .Select( g => new CustomClass()
              {
                  GroupByThisColID = g.Key,
                  ColumnSum = g.Sum( p => p.NumberIWantToSum)
              });
      

      【讨论】:

        猜你喜欢
        • 2017-01-22
        • 2017-03-25
        • 2013-06-28
        • 1970-01-01
        • 2021-08-07
        • 2012-06-27
        • 2020-11-05
        • 2011-11-01
        • 2021-10-29
        相关资源
        最近更新 更多