Linq查询具有多个计数

时间:2013-08-20 14:05:11

标签: c# sql linq linq-to-sql

我正在尝试使用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 个答案:

答案 0 :(得分: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")
        }

答案 1 :(得分: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")
})