使用GroupBy,MAX和Count

时间:2018-01-26 18:34:08

标签: c# entity-framework linq linq-to-sql

这个SQL的LINQ查询可能是什么?

SELECT PartId, BSId, 
       COUNT(PartId), MAX(EffectiveDateUtc)  
FROM PartCostConfig (NOLOCK)  
GROUP BY PartId, BSId 
HAVING COUNT(PartId) > 1 

我实际上是按两列分组并尝试为每个部分检索最大的EffectiveDateUtc。

这是我能写的。坚持根据日期提取最高记录。 也不确定,如果这是最佳的。

   //Get all the parts which have more than ONE active record with the pat 
   //effective date and for the same BSId
    var filters = (from p in configs
                            ?.GroupBy(w => new
                            {
                                w.PartId,
                                w.BSId
                            })
                            ?.Select(g => new
                            {
                                PartId = g.Key.PartId,
                                BSId = g.Key.BSId,
                                Count = g.Count()
                            })
                            ?.Where(y => y.Count > 1)
                    select p)
                    ?.Distinct()?.ToList();

    var filteredData = (from p in configs
                        join f in filters on p.PartId equals f.PartId
                        select new Config
                        {
                            Id = p.Id,
                            PartId = p.PartId,
                            BSId = p.BSId,
                            //EffectiveDateUtc = MAX(??)
                        }).OrderByDescending(x => x.EffectiveDateUtc).GroupBy(g => new { g.PartId, g.BSId }).ToList();

注意:我需要每个部分的最高记录(基于日期)。试图看看我是否可以避免循环。

2 个答案:

答案 0 :(得分:2)

等效查询将是:

var query =
    from p in db.PartCostConfig
    group p by new { p.PartId, p.BSId } into g
    let count = g.Count()
    where count > 1
    select new
    {
        g.Key.PartId,
        g.Key.BSId,
        Count = count,
        EffectiveDate = g.Max(x => x.EffectiveDateUtc),
    };

答案 1 :(得分:1)

如果我理解得很好,你就是想要达到这样的目的:

var query=configs.GroupBy(w => new{ w.PartId, w.BSId})
                 .Where(g=>g.Count()>1)
                 .Select(g=>new
                           {
                              g.Key.PartId,
                              g.Key.BSId,
                              Count = g.Count(),
                              EffectiveDate = g.Max(x => x.EffectiveDateUtc)
                           });