聚合具有两个或多个具有相同值的列的行
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了聚合具有两个或多个具有相同值的列的行相关的知识,希望对你有一定的参考价值。
在asp.net c#中,我有一大堆值。我正在尝试聚合具有相同值的行并将它们的一些值相加(目标是在表中包含一个带有agreggated信息的行)...是否有一种方法可以聚合具有两个或多个具有相同值的列的行并做了第三列的总和?
表格示例:
id | column1 | column2 |column to sum
--------+---------+----------+-------------
1 | 3 | 1 |10
2 | 3 | 1 |10
3 | 3 | 2 |10
4 | 4 | 2 |10
5 | 4 | 2 |10
6 | 7 | 3 |10
7 | 7 | 3 |10
8 | 7 | 3 |10
9 | 5 | 1 |10
10 | 5 | 4 |10
目标:具有相同column1和column2值的行的“列到总和”的总和值
它会这样结束:
id | column1 | column2 |column to sum
--------+---------+----------+-------------
- | 3 | 1 |20
3 | 3 | 2 |10
- | 4 | 2 |20
- | 7 | 3 |30
9 | 5 | 1 |10
10 | 5 | 4 |10
有没有办法用EF或LINQ或SQL语句执行此操作?
谢谢
答案
在SQL中,
SELECT column2, colum1, SUM(column to sum) GROUP BY column2, colum1
在LINQ查询语法中(未经测试,但应该如下所示)
var result = from res in myTableOrClassList
group res by new { res.Column1, res.Column2 } into g
select new { column1 = g.Key.column1, colum2 = g.Key.column2, columnSum = g.Sum(f => f.columToSum) };
Linq方法语法
var linq = myTableOrClassList.GroupBy(p=> new { p.Column1, p.Column2 }).
Select(k=> new {column1 = k.Key.Column1, column2 = k.Key.Column2, sumColumn = k.Sum(each => each.columToSum) });
另一答案
简单的GROUP BY
应该做你的工作。如果你选择id
,你会得到多余的columnToSum
。
WITH CTE AS (
SELECT 1 as id, 3 as column1, 1 as column2,10 as [column to sum]
UNION
SELECT 2 as id, 3 as column1, 1 as column2,10 as [column to sum]
UNION
SELECT 3 as id, 3 as column1, 2 as column2,10 as [column to sum]
UNION
SELECT 4 as id, 4 as column1, 2 as column2,10 as [column to sum]
UNION
SELECT 5 as id, 4 as column1, 2 as column2,10 as [column to sum]
UNION
SELECT 6 as id, 7 as column1, 3 as column2,10 as [column to sum]
UNION
SELECT 7 as id, 7 as column1, 3 as column2,10 as [column to sum]
UNION
SELECT 8 as id, 7 as column1, 3 as column2,10 as [column to sum]
UNION
SELECT 9 as id, 5 as column1, 1 as column2,10 as [column to sum]
UNION
SELECT 10 as id, 5 as column1, 4 as column2,10 as [column to sum]
)
SELECT column1,column2,SUM([column to sum]) [column to sum] FROM CTE
GROUP BY column1,column2
以上是关于聚合具有两个或多个具有相同值的列的行的主要内容,如果未能解决你的问题,请参考以下文章
在具有循环或 lambda 的多个数据帧中添加具有相同字符串值的列的更有效方法?