2016-05-05 12 views
-2

这是我的SQL命令:我需要SQL转换到LINQ

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

VAR V1 =(从ghostEntities.DeviceMasters p 将C在p.Id ghostEntities.DeviceLists等于c.DeviceMasterId 选择新table_Model { 编号= c.Id, 数量= c.Qty.Value, 月= c.DMonth, 品牌= p.Brand , model = p.Mod el, memory = p.Memory })。ToList(); –

+0

我正在从两个表中获取值......但不能将它们分组或添加值.. –

回答

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

嗨,品牌和品牌计数的作品,但设备数量是一个错误。 –

+0

什么是错误? – user3185569

+0

不能隐式转换类型'int?'到'int'。存在明确的转换(您是否缺少演员?) –

2

你应该添加组到您的LINQ查询和使用distinct()COUNT()和总和()聚合函数:

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的样本,我希望它会帮助你。

+0

实际上,此行“g.Sum(x => x.Qty)”不会编译,x将是DeviceMaster类型的,并且而不是DeviceList – user3185569