简体   繁体   中英

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

I have the following LINQ Query:

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?

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.

Averaging by month over an arbitrary period is conceptually tricky: how many months are in the period of (say) February 16th to April 7th? 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.

You need to use a GROUP BY to group the entries by day, documented here (with samples)

Otherwise you'll need to settle for doing an average via SUM/COUNT which gives you less insight into the distribution, trends, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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