Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count how many duplicates there are for each distinct value in sqlite?

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....

:)

like image 744
Chris Denman Avatar asked Apr 02 '11 10:04

Chris Denman


People also ask

How do I COUNT distinct occurrences in SQL?

To count the number of different values that are stored in a given column, you simply need to designate the column you pass in to the COUNT function as DISTINCT . When given a column, COUNT returns the number of values in that column. Combining this with DISTINCT returns only the number of unique (and non-NULL) values.

Can we use COUNT with distinct?

Yes, you can use COUNT() and DISTINCT together to display the count of only distinct rows.

Does COUNT distinct include repeating values?

It gives the counts of rows. It does not eliminate duplicate values. It considers all rows regardless of any duplicate, NULL values. It gives a distinct number of rows after eliminating NULL and duplicate values.

How can we COUNT distinct records?

SELECT COUNT (DISTINCT item_num) FROM items; If the COUNT DISTINCT function encounters NULL values, it ignores them unless every value in the specified column is NULL. If every column value is NULL, the COUNT DISTINCT function returns zero (0).


2 Answers

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;

like image 181
Bhoom Suktitipat Avatar answered Sep 27 '22 01:09

Bhoom Suktitipat


A quick google gave me this: http://www.mail-archive.com/[email protected]/msg38339.html

select type, count(type) from table group by type; 
like image 27
Håvard Avatar answered Sep 25 '22 01:09

Håvard