0

I have a datatable that looks like below which have been populated from Database

enter image description here

How can i make the result to look like below

enter image description here

Sorry for my bad explanation,Thank you very much

Ku Han
  • 49
  • 1
  • 1
  • 6

2 Answers2

1

You would need to write something like this:

Select
PN,
[Description],
Sum(January) AS January,
Sum(February) AS February,
Sum(March) AS March,
Sum(April) AS April
FROM [YourTable]
GROUP BY
PN,
[Description]
Brimbles
  • 11
  • 1
  • The thing is , this datatable i have manually insert row from another datatable, is there anyway to use C# to di it? – Ku Han Sep 24 '20 at 03:19
0

If you want to do it with Datatable instead of SQL you can use:

dt = dt.AsEnumerable()
       .GroupBy(r => new {PN = r["PN"], Description = r["Description"]})
       .Select(g => 
       {  
            var row = dt.NewRow();

            row["PN"] =  g.Key.PN;
            row["Description"] = g.Key.Description;
            row["January"] =  g.Sum(r => r.Field<int>("January"));
            row["February"] =  g.Sum(r => r.Field<int>("February"));
            row["March"] =  g.Sum(r => r.Field<int>("March"));
            row["April"] =  g.Sum(r => r.Field<int>("April"));
            
            return row;
       
       })
       .CopyToDataTable();

See: How do I use SELECT GROUP BY in DataTable.Select(Expression)?

Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28