我正在尝试使用 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
最佳答案
如果你想让它工作,你必须按两个字段分组 像这样的东西:
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")
}
关于c# - 具有多个计数的 Linq 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18337125/