使用Linq查询进行多个计数

5

我正在尝试使用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")
            }

我不知道我的查询有什么问题,一直收到这个消息:

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的问题,可能是你的连接出了问题。 - King King
1
你的表格有多少行? - CaveCoder
@DaveBish 我测试了一些其他的查询,它们都正常工作。 - Zack09
1
运行 SQL Profiler 查看数据库是否受到影响。如果是,查看生成/执行的 SQL,确定是 LINQ 问题还是 SQL 问题。 - Ocelot20
3
真可惜,逃避而不是理解和解决问题 :) - BartoszKP
显示剩余9条评论
2个回答

5
如果想让它正常工作,您需要按两个字段进行分组,例如:
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")
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接