简体   繁体   中英

Linq query with multiple count

I am trying to query this table using LINQ:

在此处输入图片说明

Here's what I want to do:

在此处输入图片说明

Here's my LINQ query:

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")
            }

I don't know what's wrong with my query, I keep getting this message:

在此处输入图片说明

Alternative Solution:

Sql query:

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

You have to group by two fields if you want it to work something like:

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")
        }

In VB.Net code is like that

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")
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM