Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

c# - LINQ or SQL: Group by with a sum of distinct values

I have a database table, on SQL Server 2019, containing a time series of prices collected with multiple frequencies (daily, weekly or monthly) which I query using EF Core 3.1

I'm trying to extract these prices, aggregated by month, but without losing the information of the collection frequency.

From the following set of data:

enter image description here

I'm trying to get this one, which contains the aggregate average value of the prices, grouped by Month, and with the frequencies of the raw records.

enter image description here

These could be easily solved by using

string.Join(",",s.Select(innerSel=>innerSel.OriginalFrequency).Distinct())

but unfortunately, I can't use as I need to work on IQueriable objects and run the execution of the LINQ query only at the end when I take a subset of data, based on the page-size, because converting to a List the query before grouping means to get several thousands of records from the DB.

I was trying to use a combination of SUM and COUNT of the frequencies in order to easily understand which is the original combination by multiplication these two values (see the schema below) but the COUNT and SUM should count only distinct values, otherwise, it doesn't work.

enter image description here

Is there a way to not lose this information in some way, without overloading the database server requesting unnecessary data, or making multiple requests?

This is the code where I'm stuck:

var aggregatedMonthlyPrices = prices.GroupBy(g => new
    {
        g.DateMonth,
        g.DateYear
    }).Select(s => new
    {
        DateMonth = s.Key.DateMonth,
        DateYear = s.Key.DateYear
        Price=s.Average(avg=>avg.Price),
        FrequencySum= s.Sum(sum=>sum.DataCollectionFrequencyId),
        FrequencyCount = s.Count(),
    });
question from:https://stackoverflow.com/questions/66065994/linq-or-sql-group-by-with-a-sum-of-distinct-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...