开发者

COUNT of DISTINCT items in a column

开发者 https://www.devze.com 2023-02-24 15:11 出处:网络
Here\'s the SQL that works (strangely) but still just returns the COUNT of all items, not the COUNT of DISTI开发者_C百科NCT items in the column.

Here's the SQL that works (strangely) but still just returns the COUNT of all items, not the COUNT of DISTI开发者_C百科NCT items in the column.

SELECT DISTINCT(COUNT(columnName)) FROM tableName;


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.


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.


SELECT COUNT(*) FROM (SELECT DISTINCT columnName FROM tableName);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号