var query = from c in context.Auto
join r in context.Label on c.idAutoChar equals r.idAutoChar
join g in context.Rent on c.idAuto equals g.idAuto
where c.idAutoChar == r.idAutoChar && c.idAuto == g.idAuto
group new {c, r, g} by new {c.idAuto, r.Name, c.RegNumber, g.Summ} into v
select new
{
v.Key.idAuto,
v.Key.Name,
v.Key.RegNumber,
Sum = (from b in v select v.Key.Summ).Sum()
};
我需要用SUM(SUM(列按idAuto对汽车进行分组,但它没有正确工作。你能帮忙吗。
var query = from c in context.Auto
join r in context.Label on c.idAutoChar equals r.idAutoChar
join g in context.Rent on c.idAuto equals g.idAuto
//where c.idAutoChar == r.idAutoChar && c.idAuto == g.idAuto //???
group new {c, r, g} by new {c.idAuto, r.Name, c.RegNumber} into v
select new
{
v.Key.idAuto,
v.Key.Name,
v.Key.RegNumber,
Sum = v.Sum(item => item.Key.Summ)
};
使用Sum = v.Sum(item => item.Key.Summ)
,不要按Summ
分组,否则它将为每个不同的Summ
值生成一个分组项。
顺便说一句,你为什么需要where
条件——它复制了你加入的on
条件
假设g.Summ是一个你想求和的数值,而不是你真正想分组的数值,那么它就不应该是键的一部分。
我没有办法测试这个,但像这样的东西可能是答案:
c in context.Auto
join r in context.Label on c.idAutoChar equals r.idAutoChar
join g in context.Rent on c.idAuto equals g.idAuto
where c.idAutoChar == r.idAutoChar && c.idAuto == g.idAuto
group new {c, r, g} by new {c.idAuto, r.Name, c.RegNumber} into v
select new
{
v.Key.idAuto,
v.Key.Name,
v.Key.RegNumber,
Sum = (from b in v
select b.Summ).Sum()
};
请注意,我们没有将c.Sum包含在分组by中,然后Sum超过b.Sum。我还认为在这个linq语句中实际上不需要g(Rent?(。