4

我正在尝试使用 LINQ 查询此表:

在此处输入图像描述

这是我想要做的:

在此处输入图像描述

这是我的 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")
            }

我不知道我的查询出了什么问题,我不断收到这条消息:

在此处输入图像描述

替代解决方案:

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
4

2 回答 2

4

如果你想让它工作,你必须按两个字段分组:

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")
        }
于 2013-08-26T21:22:00.113 回答
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")
})
于 2013-09-06T07:55:24.827 回答