我想得到每个月的计数,但即使有多次出现,计数也应该每天最多一次。我有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。谢谢!
答案 0 :(得分:8)
@Rick给出的每LINQ to SQL using GROUP BY and 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()
。
答案 1 :(得分: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()
})