Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 5 and Pivot table, How?

I've got a simple table: Year - Quarter - Value 2012 1 177 2012 2 213 2012 3 168 2012 4 313

I want to return the data via Linq as this:

Year - Q1 - Q2 - Q3 - Q4 2012 177 213 168 313

Any suggestions on the best way to do this? I assume some sort of Pivot?

TIA J

like image 910
John S Avatar asked Feb 23 '26 13:02

John S


1 Answers

This is what I worked out:

 Metrics.GroupBy(c => c.Year) 
 .Select(g => new {
Year = g.Key,
Q1 = g.Where(c => c.Quarter == 1).Sum(c => c.Value), 
      Q2 = g.Where(c => c.Quarter == 2).Sum(c => c.Value), 
Q3 = g.Where(c => c.Quarter == 3).Sum(c => c.Value),
Q4 = g.Where(c => c.Quarter == 4).Sum(c => c.Value) 
})

Any better suggestions?

like image 104
John S Avatar answered Feb 27 '26 02:02

John S