这是我的sql命令:
select
b.Brand,
count(b.Brand) as BrandCount,
SUM(a.Qty) as DeviceCount
from (
select * from DeviceList
) as a
join DeviceMaster as b
on a.DeviceMasterId = b.Id
group by b.Brand
这是我到目前为止所尝试的内容:
var v1 = (from p in ghostEntities.DeviceMasters
join c in ghostEntities.DeviceLists on p.Id equals c.DeviceMasterId
select new table_Model {
Id = c.Id,
qty = c.Qty.Value,
month = c.DMonth,
brand = p.Brand,
model = p.Model,
memory = p.Memory
}).ToList();
我从两个表中获取值,但不能对它们进行分组或添加值。
答案 0 :(得分:2)
您应该在您的LINQ查询中添加group by并使用Distinct()。Count()和Sum()聚合函数:
var query = from a in ghostEntities.DeviceList
join b in ghostEntities.DeviceMaster on a.DeviceMasterId equals b.Id
group b by b.Brand into g
select new { g.Key, count =g.Select(x => x.Brand).Distinct().Count(), sum = g.Sum(x => x.Qty) };
你可以在https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b找到很多LINQ样本,我希望它能为你提供帮助。
答案 1 :(得分:1)
按表格分组后,会失去对联接操作中其他表格字段的访问权限,可能的解决方法是:
var results = (from a in DeviceList
join b in DeviceMaster
on a.DeviceMasterId equals b.Id
group new { a, b } by new { b.Brand } into grp
select new
{
Brand = grp.Key.Brand,
BrandCount = grp.Count(),
DeviceCount = grp.Sum(x=> x.a.Qty.GetValueOrDefault())
}).ToList();