[英]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 - 我有正确的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)
Could anyone help me translating the above query to LINQ. 任何人都可以帮我翻译上面的查询到LINQ。 Thanks! 谢谢!
Per LINQ to SQL using GROUP BY and COUNT(DISTINCT) given by @Rick, this should work: 对于使用 @Rick给出的GROUP BY和COUNT(DISTINCT)的LINQ to SQL ,这应该有效:
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.
我不知道L2S是否可以正确转换内部
g.Select(act => act.Date.Day).Distinct.Count()
。
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()
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.