简体   繁体   English

c#/ LINQ-一段时间内每天,每周和每月的平均查询数量

[英]c# / LINQ - Average the number of enquiries per day, week and month over a time period

I have the following LINQ Query: 我有以下LINQ查询:

model.TotalEnquiries = enquiriesDbContext.Enquiries.Where(x => x.CustomerAccountNumber == formModel.CustomerAccNo)
                   .Where(x => x.EnquiryDate >= startDate).Where(x => x.EnquiryDate <= endDate).Count();

This works fine as it'll return a value of say, 60, between 2 specified time periods, but what I'd like to do is find the average number of enquiries per day, week and month for this period, is it possible in LINQ? 这可以正常工作,因为它将在两个指定的时间段之间返回值60,但是我想做的是找到该时间段内每天,每周和每月的平均查询次数,是否可以LINQ?

Well given that you've specified the period yourself, it's easy: 好了,既然您自己指定了期限,这很简单:

var averagePerDay = total / (endDate - startDate).TotalDays;

EDIT: I see you're changing the goalposts... if you want to get averages for different date ranges in one query then it's going to be tricky. 编辑:我看到你正在改变球门柱...如果你想在一个查询中获得不同日期范围的平均值,那将非常棘手。 Personally, unless there's a huge amount of data, I'd probably fetch all the enquiry dates within the appropriate range, and then process it locally, which is likely to be easier than trying to minimize the number of SQL queries while still keeping them smart. 就个人而言,除非有大量数据,否则我可能会获取适当范围内的所有查询日期,然后在本地进行处理,这可能比尝试尽量减少SQL查询的数量同时保持其智能还容易。 。

Averaging by month over an arbitrary period is conceptually tricky: how many months are in the period of (say) February 16th to April 7th? 从概念上讲,在任意时期内按月进行平均是很棘手的:(例如)2月16日至4月7日有多少个月? Three different month lengths are involved. 涉及三个不同的月份长度。

Of course, you may mean "average by day, grouping by month" (eg average by day in January, average by day in February" etc) which is entirely different. This is why you need to be precise about requirements. 当然,您可能会说“每天平均,按月分组”(例如,1月的平均天数,2月的平均天数”等),这是完全不同的,这就是为什么您需要精确了解需求的原因。

You need to use a GROUP BY to group the entries by day, documented here (with samples) 您需要使用GROUP BY按日期对条目进行分组, 此处记录 (带有示例)

Otherwise you'll need to settle for doing an average via SUM/COUNT which gives you less insight into the distribution, trends, etc. 否则,您需要通过SUM / COUNT进行平均值计算,这会使您对分布,趋势等情况的了解减少。

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

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