Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COUNT of DISTINCT items in a column

Here's the SQL that works (strangely) but still just returns the COUNT of all items, not the COUNT of DISTINCT items in the column.

SELECT DISTINCT(COUNT(columnName)) FROM tableName;
like image 662
blunders Avatar asked Apr 14 '11 18:04

blunders


People also ask

What is the formula for distinct count in Excel?

Counting Unique Values in Excel. Unique value in excel appears in a list of items only once and the formula for counting unique values in Excel is “=SUM(IF(COUNTIF(range,range)=1,1,0))”. The purpose of counting unique and distinct values is to separate them from the duplicates of a list of Excel.

Can we use count with distinct in SQL?

Yes, you can use COUNT() and DISTINCT together to display the count of only distinct rows. SELECT COUNT(DISTINCT yourColumnName) AS anyVariableName FROM yourTableName; To understand the above syntax, let us create a table.


3 Answers

SELECT COUNT(*) FROM tableName

counts all rows in the table,

SELECT COUNT(columnName) FROM tableName

counts all the rows in the table where columnName is not null, and

SELECT (DISTINCT COUNT(columnName)) FROM tableName

counts all the rows in the table where columnName is both not null and distinct (i.e. no two the same)

SELECT DISTINCT(COUNT(columnName)) FROM tableName

Is the second query (returning, say, 42), and the distinct gets applied after the rows are counted.

like image 101
Philip Kelley Avatar answered Sep 28 '22 00:09

Philip Kelley


You need

SELECT COUNT(DISTINCT columnName) AS Cnt
FROM tableName;

The query in your question gets the COUNT (i.e. a result set with one row) then applies Distinct to that single row result which obviously has no effect.

like image 44
Martin Smith Avatar answered Sep 28 '22 01:09

Martin Smith


SELECT COUNT(*) FROM (SELECT DISTINCT columnName FROM tableName);
like image 39
Daniel DiPaolo Avatar answered Sep 28 '22 00:09

Daniel DiPaolo