在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语句执行此操作?
谢谢
答案 0 :(得分:3)
在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) });
答案 1 :(得分:0)
简单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