我尝试了几种不同的方法,我对生成的输出查询印象不深。这似乎效率低下。它需要高效,不应该将所有行带回应用层
select year(datetaken) as yr,
month(datetaken) as mth,
day(datetaken) as dy,
count(*) as totalpics
from photos
where photos.dateTaken <= @cutoffdate
group by year(datetaken), month(datetaken), day(datetaken)
order by yr asc, mth asc, dy asc
LINQ查询:
var query = ctx.Photos.Where(p => p.DateTaken <= maxCutOffDate)
.GroupBy(p => new { p.DateTaken.Year, p.DateTaken.Month, p.DateTaken.Day })
.Select(grp => grp);
var results = query.ToList();
答案 0 :(得分:3)
仅选择分组键(grp.Key
):
var query = ctx.Photos.Where(p => p.DateTaken <= maxCutOffDate)
.GroupBy(p => new { p.DateTaken.Year, p.DateTaken.Month, p.DateTaken.Day })
.Select(grp => grp.Key);
var results = query.ToList();
修改强>
或者,包括totalpics的count
:
var query = ctx.Photos.Where(p => p.DateTaken <= maxCutOffDate)
.GroupBy(p => new { p.DateTaken.Year, p.DateTaken.Month, p.DateTaken.Day })
.Select(grp => new
{
Date = grp.Key,
TotalPics = grp.Count()
});
var results = query.ToList();
答案 1 :(得分:1)
您可以通过grp.Key
访问关键属性,并通过grp.Count()
访问。
var query = ctx.Photos.Where(p => p.DateTaken <= maxCutOffDate)
.GroupBy(p => new { p.DateTaken.Year, p.DateTaken.Month, p.DateTaken.Day })
.Select(grp => new
{
grp.Key.Year,
grp.Key.Month,
grp.Key.Day,
Count = grp.Count()
});
var results = query.ToList();