添加日期:2016-11-18
SQL中distinct的用法详解教程:
一、COUNT统计
select count(distinct name) from A,表中name去重后的数目,SQL Server可以支持,但是Access不支持。count是不能统计多个字段的,下面的SQL在SQL Server和Access中都无法运行。select count(distinct name, id) from A,若想使用,请使用嵌套查询,如下:
select count(*) from (select distinct xing, name from B) AS M
二、distinct必须放在开头
select id, distinct name from A,会提示错误,因为distinct必须放在开头。
三、作用于单列
select distinct name from A,执行后结果如下:
四、作用于多列
select distinct name, id from A,执行后结果如下:
实际上是根据name与id 2个字段来去重的,这种方式Access和SQL Server同时支持。
select distinct xing, ming from B,返回如下结果:
返回的结果为2行,这说明distinct并非是对xing和ming两列“字符串拼接”后再去重的,而是分别作用于了xing与ming列。
五、其它
distinct语句中select显示的字段只能是distinct指定的字段,其它字段是不可能出现的。例如,假如表A有“备注”列,如果想获取distinc name,以及对应的“备注”字段,想直接通过distinct是不可能实现的。