2013-08-20 48 views
4

我想查询使用LINQ此表:Linq查询与多个计数

enter image description here

这就是我想做的事:

enter image description here

这里是我的LINQ查询:

var query = from a in table 
      where a.Country.Equals("USA") 
      group a by a.Product_brand into grp 
      select new 
      { 
       Product_brand = grp.key.Product_brand, 
       Country = grp.Key.Country, 
       Black = grp.Count(a => a.Black=="Yes"), 
       White = grp.Count(a => a.White=="Yes"), 
       Red = grp.Count(a=> a.Red=="Yes"), 
       Green = grp.Count(a=> a.Green=="Yes") 
      } 

我不知道我的问题有什么问题RY,我不断收到这样的信息:

enter image description here

替代解决方案:

SQL查询:

SELECT [Product brand], Country, 
sum(case when [Black] = 'Yes' then 1 else 0 end) as Black, 
sum(case when [White] = 'Yes' then 1 else 0 end) as White, 
sum(case when [Red] = 'Yes' then 1 else 0 end) as Red, 
sum(case when [Green] = 'Yes' then 1 else 0 end) as Green, 
FROM   dbo.Table 

group by [Product brand], Country 
+2

这似乎没有在linq的一些问题,也许它在你的连接。 –

+0

您的服务器已关闭或无法访问?你的查询看起来很好:只要你的表的大小不在数十亿行中,你就应该很快得到你的结果。 – dasblinkenlight

+0

服务器肯定没有关闭,我只是测试了连接它正在工作 – Zack09

回答

3

,如果你想要的工作 像你要组由两个字段:

var query = from a in table 
     where a.Country.Equals("USA") 
     group a by new {a.Product_brand, a.Country} into grp 
     select new 
     { 
      Product_brand = grp.key.Product_brand, 
      Country = grp.Key.Country, 
      Black = grp.Count(a => a.Black=="Yes"), 
      White = grp.Count(a => a.White=="Yes"), 
      Red = grp.Count(a=> a.Red=="Yes"), 
      Green = grp.Count(a=> a.Green=="Yes") 
     } 
0

在VB.Net代码是像那

Dim query=(from a in table 
where a.Country = "USA" 
group a by a.Product_brand,a.country into grp = group _ 
select new with 
{ 
    .Product_brand=Product_brand, 
    .country=country, 
    .Black = grp.Count(Function(a) a.Black="Yes"), 
    .White = grp.Count(Function(a) a.White="Yes"), 
    .Red = grp.Count(Function(a) a.Red="Yes"), 
    .Green = grp.Count(Function(a) a.Green="Yes") 
})