开发者

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(da开发者_运维知识库te) 

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


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.


var results = db.activities.Where(a => a.id == myID)
                           .GroupBy(a => new 
                                         {
                                             Month = a.date.Month, 
                                             Year = a.date.Year
                                         })
                           .Select(g => new
                                        {
                                            Month = g.Key.Month,
                                            Year = g.Key.Year,
                                            Monthly_Count = g.Select(d => d.date.Day)
                                                             .Distinct()
                                                             .Count()
                                        })
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜