Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a comparable LINQ query for aggregate distinct count in sql?

I want to get a count for each month but count should be only at most one per day even if there are multiple occurences . I have the SQL query which works right but having trouble to convert it into LINQ -

select 
    count(DISTINCT DAY(date)) as Monthly_Count,
    MONTH(date) as Month,
    YEAR(date)
from 
    activity
where 
    id=@id
group by
    YEAR(date),
    MONTH(date) 

Could anyone help me translating the above query to LINQ. Thanks!

like image 786
Vishal Avatar asked Jul 26 '11 20:07

Vishal


People also ask

How to use distinct method in LINQ?

Examples. The following code example demonstrates how to use Distinct<TSource>(IEnumerable<TSource>) to return distinct elements from a sequence of integers. If you want to return distinct elements from sequences of objects of some custom data type, you have to implement the IEquatable<T> generic interface in the class ...

How to use distinct in LINQ query in c#?

C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).

What are aggregate functions in LINQ?

In LINQ, aggregation functions are those functions which are used to calculate a single value from the collection of the values. Real life example of aggregation function is calculating the annual rainfall occurred in 2018 according to readings collected whole year.

How do I get distinct on a single column in LINQ?

distinct in Linq to get result based on one field of the table (so do not require a whole duplicated records from table). I know writing basic query using distinct as followed: var query = (from r in table1 orderby r. Text select r).


1 Answers

Per LINQ to SQL using GROUP BY and COUNT(DISTINCT) given by @Rick, this should work:

var query = from act in db.Activity
            where act.Id == id
            group act by new { act.Date.Year, act.Date.Month } into g
            select new
            {
                MonthlyCount = g.Select(act => act.Date.Day).Distinct().Count(),
                Month = g.Key.Month,
                Year = g.Key.Year
            };

I don't know if L2S can convert the inner g.Select(act => act.Date.Day).Distinct.Count() properly.

like image 157
user7116 Avatar answered Oct 27 '22 23:10

user7116