c# - 具有多个计数的 Linq 查询

标签 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

最佳答案

如果你想让它工作,你必须按两个字段分组 像这样的东西:

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/

相关文章:

c# - 如何从linq查询中提取条件语句?

c# - 搜索字符串数组中包含的字典键

c# - 构建 Linq 通用查询

c# - 调度程序.CurrentDispatcher.Invoke

c# - 调试javascript代码

c# - 将 nvarchar 值转换为数据类型 int 时转换失败

mysql - 在 phpMyAdmin 中将 mysql 导出为 ASCII

c# - Entity Framework 运行存储过程和 native 查询性能注意事项

c# - LINQ:已添加具有相同键的项目

sql - Mysql 查询返回带有 in 和 find_int_set 的重复条目