6

我想获得每个月的计数,但计数应该每天最多只有一个,即使有多次出现。我的 SQL 查询可以正常工作,但无法将其转换为 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) 

谁能帮我把上面的查询翻译成 LINQ。谢谢!

4

2 回答 2

8

每个LINQ to SQL 使用@Rick 给出的 GROUP BY 和 COUNT(DISTINCT) ,这应该有效:

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
            };

我不知道 L2S 是否可以g.Select(act => act.Date.Day).Distinct.Count()正确转换内部。

于 2011-07-26T20:47:24.420 回答
0
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()
                                        })
于 2011-07-26T20:48:01.370 回答