SELECT DISTINCT(COUNT(*))究竟做了什么?

时间:2014-09-25 18:11:01

标签: sql

我使用了以下查询,它返回了我希望它返回的内容,但是我很难绕过查询所做的事情。

查询并不比标题中的内容更为精彩:select distinct(count(*)) from table1

2 个答案:

答案 0 :(得分:4)

SQL中不需要区别,因为您将只获得结果,count(*)而不包含group by子句返回,该表中所有行的计数。

因此试试这个:

select count(*) from table1 

Distinct用于从一组值中查找不同的值:

说你有table1,其中column1为:

Column1
----------
a
a
b
b
a
c

运行sqls之后,您将获得输出:

1)select count(*) from table1

输出:6

2)select distinct(count(*)) from table1

输出:6

3)select count( distinct column1) from table1

输出:3

通常在计数内使用不同,优选使用特定列。

select count( distinct column_name_n ) from table1

答案 1 :(得分:1)

distinct是冗余的...选择Count(*),只有一个表只能生成一个值,因此不同(这将消除重复)是不可靠的。

如果您有多个输出,(例如,如果您正在对某些内容进行分组)那么它将导致查询仅为count(*)的每个不同值显示一个输出行,否则将生成... < / p>

例如,如果你有

 name
 Bob
 Bob
 Bob
 Bob
 Mary
 Mary
 Mary
 Mary
 Dave
 Dave
 Al
 George

然后

 select count(*) 
 From table 
 group By name

会导致

    4
    4
    2
    1
    1

但是

 select distinct count(*) 
 From table 
 group By name

会导致

    4
    2
    1