简体   繁体   English

计算数据库SQL中的平均值

[英]Calculate Average in Database SQL

I need to get the Average, rounded to 2 decimal points, of a difference of two dates. 我需要得到平均值,舍入到2个小数点,两个日期的差异。

Using Entity Framework Core I used the following: 使用Entity Framework Core我使用了以下内容:

var average = await games
  .Where(x => x.Finish.HasValue)
  .AverageAsync(x => Math.Round((x.Finish.Value - x.Start).TotalDays, 2));

This seems to be running in memory. 这似乎是在内存中运行。

How can I calculate the average on the database (SQL)? 如何计算数据库的平均值(SQL)?

The problem is not the Average , but the time span calculation - currently EF Core (2.x) does not support generic SQL translation of time span calculations. 问题不是Average ,而是时间跨度计算 - 当前EF Core(2.x)不支持时间跨度计算的通用SQL转换。

For SqlServer though you could use some of the DateDiff methods introduced in EF Core 2.1. 对于SqlServer,您可以使用EF Core 2.1中引入的一些DateDiff方法。 All they return int values, so you can't use directly DateDiffDay to get the equivalent of TimeSpan.TotalDays , but you could use DateDiffHour / 24d or DateDiffMinute / (24d * 60) etc. to simulate it. 所有它们都返回int值,因此您不能直接使用DateDiffDay来获得TimeSpan.TotalDays的等价物,但您可以使用DateDiffHour / 24dDateDiffMinute / (24d * 60)等来模拟它。

For instance, 例如,

var average = await games
    .Where(x => x.Finish.HasValue)
    .AverageAsync(x => Math.Round(EF.Functions.DateDiffHour(x.Start, x.Finish.Value) / 24d, 2));

translates to 翻译成

  SELECT AVG(ROUND(DATEDIFF(HOUR, [x].[Start], [x].[Finish]) / 24.0E0, 2))
  FROM [Game] AS [x]
  WHERE [x].[Finish] IS NOT NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM