努力将SQL查询转换为等效于LINQ的方法-多个联接,分组和聚合函数

时间:2019-05-02 14:54:45

标签: c# entity-framework linq

我有以下查询,可以在SQL Server Management Studio中获得预期结果:

x <- c('I want to get 10 apples, 99 bananas and 86 oranges', 'I want to buy a car')

我有以下工作linq查询:

SELECT 
    u.DisplayName,
    up.ColorPreferences,
    SUM(rt.Score) AS Points,
    COUNT(*) AS Plans,
    MAX(pl.Created) AS MaxDate
FROM 
    [dbo].[Users] u
INNER JOIN 
    [dbo].[PlanLogs] pl ON u.Id = pl.UserId
INNER JOIN 
    [dbo].[ResourceTypes] rt ON pl.ResourceTypeId = rt.Id
INNER JOIN 
    [dbo].[UserProfile] up ON pl.UserId = up.UserId
GROUP BY 
    u.DisplayName, up.ColorPreferences;

如您所见,它缺少MaxDate。我无法访问MaxDate,因为g包含rt的属性。我尝试了以下操作,但得到“值不在预期范围内”

from u in _context.Users
join pl in _context.PlanLogs on u.Id equals pl.UserId
join rt in _context.ResourceTypes on pl.ResourceTypeId equals rt.ID
join up in _context.UserProfile on pl.UserId equals up.UserId
group rt by new { u.DisplayName, up.ColorPreferences} into g
select new
{
DisplayName = g.Key.DisplayName,
ColorPrefs = g.Key.ColorPreferences,
Points = g.Sum(x => x.Score),
Plans = g.Count()
};

如何将MaxDate添加到结果中?

谢谢

2 个答案:

答案 0 :(得分:0)

您是否尝试过访问在第一个linq查询中创建的pl。中的最大值?为什么要按rt而不是整个结果分组?试试这个吧:

from u in _context.Users
join pl in _context.PlanLogs on u.Id equals pl.UserId
join rt in _context.ResourceTypes on pl.ResourceTypeId equals rt.ID
join up in _context.UserProfile on pl.UserId equals up.UserId
group u by new { u.DisplayName, up.ColorPreferences} into g
select new
{
  DisplayName = g.Key.DisplayName,
  ColorPrefs = g.Key.ColorPreferences,
  Points = g.Sum(x => x.Score),
  Plans = g.Count(),
  MaxDate = g.Max(m => m.pl.Created)
};

答案 1 :(得分:0)

我最终把它提高了。我需要将特定的列而不是整个表传递给组:

group new { rt.Score, pl.Created } by..

而不是

group new { rt, pl } by...

工作查询:

from u in _context.Users
join pl in _context.PlanLogs on u.Id equals pl.UserId
join rt in _context.ResourceTypes on pl.ResourceTypeId equals rt.ID
join up in _context.UserProfile on pl.UserId equals up.UserId
group new { rt.Score, pl.Created } by new { u.DisplayName, up.ColorPreferences } into g
select new
{
DisplayName = g.Key.DisplayName,
ColorPrefs = g.Key.ColorPreferences,
Points = g.Sum(i => i.Score),
Plans = g.Count(),
MaxCreated = g.Max(i => i.Created).ToString("dd/MM/yyyy HH:mm")
}