Wondering
Wondering

Reputation: 5076

How to count number of same data in a column

I have a table:

Id  Catg
1   cat01
2   cat01
3   cat01
1   cat02
2   cat02

now I want to detect number of occurance of catg01 and catg02,like in this ex, catg01 is 3 times and catg02 is 2 times,I want to count that through LINQ/ simple db query. Pls note: cant use Where clause and hardcode Catg01/catg 02,as there can n number of category.Is it possible to detect? if yes then pls help.

Upvotes: 1

Views: 3486

Answers (2)

Eoin Campbell
Eoin Campbell

Reputation: 44268

Select Catg, Count(*) From TableName Group By CatG

For the LINQ Version. Imagine a Class

    class Table
    {
        public int ID { get; set; }
        public string CatG { get; set; }
    } 

Then if you had a list of that class, you could query it as follows

List<Table> y = new List<Table>();

y.Add(new Table() { ID = 1, CatG = "a" });
y.Add(new Table() { ID = 2, CatG = "a" });
y.Add(new Table() { ID = 3, CatG = "a" });
y.Add(new Table() { ID = 4, CatG = "b" });
y.Add(new Table() { ID = 5, CatG = "b" });


var query = y.GroupBy(table => table.CatG);

// Iterate over each IGrouping in the collection.
foreach (var item in query)
{
    Console.WriteLine("CatG: {0} Number of Items: {1}", item.Key, item.Count());
}

Upvotes: 5

Alnitak
Alnitak

Reputation: 339816

SELECT Catg, COUNT(*)
FROM myTable GROUP BY Catg

Upvotes: 6

Related Questions