2013-08-20 43 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") 
})