Entity framework + average part of column in SQL Server

entity-framework-core sql-server

Question

I have a table like below in SQL Server

id       datetime           temperature
1     2020-01-1 10:00          22
2     2020-01-1 10:20          23
3     2020-01-1 10:40          27
4     2020-01-1 11:00          20
5     2020-01-1 11:20          19
6     2020-01-1 10:40          10

I want to create a query that averages for any one hour like below

id       datetime           temperature
1     2020-01-1 10:00          24        */ average for 10 o clock
2     2020-01-1 11:00        16.33       */ average for 11 o clock

Can anyone assist?

1
0
4/2/2020 7:47:17 AM

Popular Answer

You can GroupBy then use Average to achieve it.

Computes the average of a sequence of numeric values.

var result = dbContext.your_table.GroupBy(p => new { p.Id, p.datetime })
                        .Select(g => new
                         {
                             id = g.Keys.Id,
                             datetime = g.Keys.datetime,
                             temperature = g.Select(p => p.temperature).Average()
                         });
0
4/2/2020 7:43:57 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow