Group data table and sum values in different columns

Hi!
I have a table like this:
Employee | 2020 | 2021 | 2022
1 |268 | 269 | 270
2 |2656| 269 | 22370
2 |2688| 2329 | 2720
3 |2878| 2659 | 20
3 |28 | 2966 | 20

I need to group by employee and sum each year (column), to be reflected in a new DT with totals per column. Can this be done with only official activities?

Thanks!

Hi @krissia.salazar.enriquez,

You need both grouping by employee and the sum of these groups by year, right?

Regards,
MY

Hi,

Can you try the following?

dtResult = dt.AsEnumerable.GroupBy(Function(r) r("Employee").ToString).Select(Function(g) dt.Clone.LoadDataRow({g.Key,g.Sum(Function(r) CInt(r("2020").ToString)),g.Sum(Function(r) CInt(r("2021").ToString)),g.Sum(Function(r) CInt(r("2022").ToString))},False)).CopyToDataTable

Sample20220603-1.zip (2.5 KB)

Regards,

In general LINQ is a good option to do this. Have a look here where at the begin a Non-LINQ approach for grouping the data is introduced

Yes, that’s what I need.

Thank you! It worked fine for the 92 columns I have to sum. However, I didn’t mention that I also have some other columns in my table I don’t need to sum (text, for example, the employee name) and when I run this it’s not showing that data… can we adjust it to show those columns also?

Hi,

In this case, we need to know which data should be kept (first row of the group etc.) and which column should be sum or not. If you can share specific sample for it, we might be able to show a sample expression.

Regards,

Thanks,
Using the same example, let’s assume we have two more columns I don’t want to sum: Employee location and Employee Name. I don’t need those to group since location may be different, but I don’t care (it can reflect the first value, for example, it can reflect Paris for Marie even though she was in Paris and London…). I need only to use the ID to group, sum by year/employee and keep the other two columns.

image

Hi,

In this case, we need to decide which row is kept in each group (especially Employee location). If the first row is kept, the following expression will work.

dtResult = dt.AsEnumerable.GroupBy(Function(r) r("Employee ID").ToString).Select(Function(g) dt.Clone.LoadDataRow({g.First().Item("Employee location"),g.First().Item("Employee Name"),g.Key,g.Sum(Function(r) CInt(r("2020").ToString)),g.Sum(Function(r) CInt(r("2021").ToString)),g.Sum(Function(r) CInt(r("2022").ToString))},False)).CopyToDataTable

Sample20220607-1.zip (14.7 KB)

Regards,

1 Like

Thank you, Yoichi, it worked perfectly!

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.