65

I have a table:

ref,type
1,red
2,red
3,green
4,blue
5,black
6,black

I want the result of a sqlite query to be:

red,2
green,1
blue,1
black,2

I think the hardest thing to do is find a question to match my problem? Then I am sure the answer is around the corner....

:)

robertspierre
  • 3,218
  • 2
  • 31
  • 46
Chris Denman
  • 1,187
  • 3
  • 9
  • 15

2 Answers2

130

My quick google with the terms "count unique values sqlite3" landed me on this post. However, I was trying to count the overall number of unique values, instead of how many duplicates there are for each category.

From Chris's result table above, I just want to know how many unique colors there are. The correct answer here would be four [4].

This can be done using select count(DISTINCT type) from table;

Cory Roy
  • 5,379
  • 2
  • 28
  • 47
Bhoom Suktitipat
  • 2,147
  • 2
  • 17
  • 11
  • 1
    And can you provide an example of the best way to use this query. Would it be `long count = DatabaseUtils.longForQuery(db, "select count(DISTINCT type) from table", null);` – ban-geoengineering Jul 04 '14 at 10:49
  • 2
    @Bhoom, count(DISTINCT type) is what I looking for today. – Ashwin Kanjariya Aug 11 '17 at 07:59
  • not what the asker was asking so no up-vote but exactly with I needed, thank you! Also I aliased the column name as `total` like this, `select count(distinct type) as total from table" – ABCD.ca Feb 24 '18 at 01:23
  • this is not what the question asked – Wes Dec 02 '22 at 20:33
71

A quick google gave me this: http://www.mail-archive.com/sqlite-users@sqlite.org/msg38339.html

select type, count(type) from table group by type;
Håvard
  • 9,900
  • 1
  • 41
  • 46