我可以通过以下方式选择一列中所有不同的值:

SELECT DISTINCT column_name FROM table_name SELECT column_name FROM table_name

但是如何从该查询中获得行数呢?是否需要子查询?


当前回答

Count(distinct({fieldname}))是多余的

简单的Count({fieldname})给你在这个表中所有不同的值。它不会(像许多人假设的那样)只给你表的Count[即不与Count(*) from table]

其他回答

注意Count()忽略空值,所以如果你需要允许null作为它自己的独特值,你可以做一些棘手的事情,比如:

select count(distinct my_col)
       + count(distinct Case when my_col is null then 1 else null end)
from my_table
/

这将为您提供不同的列值和每个值的计数。我通常发现我想知道这两方面的信息。

SELECT [columnName], count([columnName]) AS CountOf
FROM [tableName]
GROUP BY [columnName]

Count(distinct({fieldname}))是多余的

简单的Count({fieldname})给你在这个表中所有不同的值。它不会(像许多人假设的那样)只给你表的Count[即不与Count(*) from table]

不使用DISTINCT,我们可以这样做-

SELECT COUNT(C)
FROM (SELECT COUNT(column_name) as C
FROM table_name
GROUP BY column_name)
select count(*) from 
(
SELECT distinct column1,column2,column3,column4 FROM abcd
) T

这将给出不同列组的计数。