简体   繁体   English

如何使用 EF Core 3 获得 PostgreSQL 的平均日期差异

[英]How to get average date difference in PostgreSQL using EF Core 3

Using npgsql, EF Core 3 and a PostgreSQL database, I am trying to write the following SQL query in LINQ.使用 npgsql、EF Core 3 和 PostgreSQL 数据库,我正在尝试在 LINQ 中编写以下 SQL 查询。

SQL: SQL:

SELECT date("EndDate"), avg("EndDate"-"StartDate") as avg_time
FROM trip
group by date("EndDate")

LINQ: LINQ:

var q = from trip in _context.Trips
        group trip by trip.EndDate.Date into tripGroup
        select new { date = tripGroup.Key, avg_time_mins = tripGroup.Average(tg => (tg.EndDate - tg.StartDate).TotalMinutes) };

I tried with TotalMinutes , because .Average( ) does not seem to take a TimeSpan.我尝试使用TotalMinutes ,因为.Average( )似乎不需要 TimeSpan。 All efforts ended up with a runtime exception stating that this construct is not supported and suggesting to rewrite the query.所有努力都以运行时异常告终,指出不支持此构造并建议重写查询。

If u want to TimeSpan as average using Linq(that what I understand from question) first u have to understand average will be done in memory.如果您想使用 Linq 将 TimeSpan 作为平均值(我从问题中理解)首先您必须了解平均值将在 memory 中完成。

var groups = await _context.Trips.GroupBy(trip =>trip.EndDate.Date).ToArrayAsync() // load Them in memory

var q = groups.Select(group=> {
    var timeSpans = group.Select(trip=>trip.EndDate - trip.StartDate);
    var avg = GetAverage(timeSpans)
    return new {group.key, avg }
}).ToArray()


TimeSpan GetAverage(IEnumerable<TimeSpan> timeSpans){
 var average= timeSpans.Average(x => x.TotalMilliseconds)
 return TimeSpan.FromMilliseconds(average);
} 

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

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