0

我尝试了几种不同的方法,但生成的输出查询并没有给我留下深刻的印象。看起来效率太低了。它需要高效并且不应该将所有行带回应用层

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();
4

2 回答 2

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();

编辑

或者,包括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();
于 2012-12-29T16:27:58.027 回答
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();
于 2012-12-29T18:18:33.317 回答