I want to do a query with linq (list of objects) and I really don't know how to do it, I can do the group and the sum but can't select rest of the fields. Example:
ID Value Name Category 1 5 Name1 Category1 1 7 Name1 Category1 2 1 Name2 Category2 3 6 Name3 Category3 3 2 Name3 Category3
I want to group by ID, SUM by Value and return all fields like this.
ID Value Name Category 1 12 Name1 Category1 2 1 Name2 Category2 3 8 Name3 Category3
Use DataFrame. groupby(). sum() to group rows based on one or multiple columns and calculate sum agg function. groupby() function returns a DataFrameGroupBy object which contains an aggregate function sum() to calculate a sum of a given column for each group.
SUM is used with a GROUP BY clause. The aggregate functions summarize the table data. Once the rows are divided into groups, the aggregate functions are applied in order to return just one value per group. It is better to identify each summary row by including the GROUP BY clause in the query resulst.
We can group the resultset in SQL on multiple column values. When we define the grouping criteria on more than one column, all the records having the same value for the columns defined in the group by clause are collectively represented using a single record in the query output.
Yes, it is possible to use MySQL GROUP BY clause with multiple columns just as we can use MySQL DISTINCT clause. Consider the following example in which we have used DISTINCT clause in first query and GROUP BY clause in the second query, on 'fname' and 'Lname' columns of the table named 'testing'.
Updated : If you're trying to avoid grouping for all the fields, you can group just by Id
:
data.GroupBy(d => d.Id) .Select( g => new { Key = g.Key, Value = g.Sum(s => s.Value), Name = g.First().Name, Category = g.First().Category });
But this code assumes that for each Id
, the same Name
and Category
apply. If so, you should consider normalizing as @Aron suggests. It would imply keeping Id
and Value
in one class and moving Name
, Category
(and whichever other fields would be the same for the same Id
) to another class, while also having the Id
for reference. The normalization process reduces data redundancy and dependency.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With