Search code examples
c#asp.netqsqldatabase

C# SQL table select and count distinct values


i have ASP website with SQL database table. in this table column mane "type". i want to get all distinct values from this column with values count in datatable. for example for database table:

id  type
---------
1   type1
2   type2
3   type3
4   type2
5   type2
6   type3

i want to get the following datatable:

type  count
------------
type1   1
type2   3
type3   2

Solution

  • You can use

    SELECT type, COUNT(type) as count
    FROM Table1 
    GROUP BY type
    

    Result

    |  type | count |
    |-------|-------|
    | type1 |     1 |
    | type2 |     3 |
    | type3 |     2 |
    

    SqlFiddle DEMO