简体   繁体   中英

COUNT of DISTINCT items in a column

这是可行的SQL(奇怪),但仍然只返回所有项目的COUNT,而不是列中DISTINCT项目的COUNT。

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 (ie 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 (ie 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM