Skip to content
Advertisement

sqlite count of distinct occurrences

What is the best way of writing a sqlite query that will count the occurrences of colC after selecting distinct colA’s ?

Notice ColA needs to be distinct.

Example

Although close, these results are incorrect.

enter image description here

It should return:
123 a cat 1
124 b dog 1
125 e snake 2
126 f fish 1
127 g snake 2

Advertisement

Answer

Explanation:

First subquery (inside WITH) gets desired result but without count column. Second subquery (inside JOIN) counts each colC value repetition in desired result and this count is returned to final result.

There very helpful WITH clause as result of first subquery is used in two places. More info: https://www.sqlite.org/lang_with.html


Query for SQLite before version 3.8.3:

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement