paguirre82
New member
- Joined
- Jun 13, 2021
- Messages
- 2
- Programming Experience
- 1-3
0
I've been struggling for a few days to display something like Pivoting a dynamic table on SQL, using Linq. I don't actually want to create a pivoted table, I just want to display the results as if it was a pivoted table.
I have two entities:
Category:
StaticEvent:
I'm trying to generate a table showing the COUNT of STATIC EVENTS per CATEGORY PER YEARMONTH. So the rows would be the YEARMONTH, the columns would be the Categories and the values would be the COUNT.
I got to the point where I can count the STATIC EVENTS per YEARMONTH:
but I'm lost about what to do from here.
I can easily do it in SQL with this query :
Any help will be enormously appreciated
I've been struggling for a few days to display something like Pivoting a dynamic table on SQL, using Linq. I don't actually want to create a pivoted table, I just want to display the results as if it was a pivoted table.
I have two entities:
Category:
C#:
public int Id { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
public ICollection<StaticEvent> StaticEvents { get; set; }
StaticEvent:
C#:
public int Id { get; set; }
public int CategoryId {get; set; }
public Category Category { get; set; }
public DateTimeOffset Time {get; set; }
[MaxLength(500)]
public string Comment {get; set;}
I'm trying to generate a table showing the COUNT of STATIC EVENTS per CATEGORY PER YEARMONTH. So the rows would be the YEARMONTH, the columns would be the Categories and the values would be the COUNT.
I got to the point where I can count the STATIC EVENTS per YEARMONTH:
C#:
var query = _context.Categories
.SelectMany(c => c.StaticEvents )
.GroupBy(c =>
new {
Year = c.Time.Year,
Month = c.Time.Month
})
.Select( x=> new {YearMonth = x.Key, Count = x.Count()})
.ToList();
foreach (var x in query)
{Console.WriteLine($"Month = {x.YearMonth.Year},{x.YearMonth.Month}, , Count = " + x.Count);}
but I'm lost about what to do from here.
I can easily do it in SQL with this query :
C#:
SELECT @cols = @cols + QUOTENAME(categoryId) + ',' FROM (select distinct categoryId from StaticEvents) as tmp
SELECT @Cols = SUBSTRING(@cols, 0, len(@cols)) --trim "," at end
SET @query =
'SELECT * FROM
(
select Month(Time) as Month, Id, categoryID from StaticEvents
) src
pivot
(
Count(Id) for categoryId in (' + @cols + ')
) piv'
EXECUTE (@query)
Any help will be enormously appreciated
Last edited by a moderator: