您好,欢迎访问一九零五行业门户网

SQL中distinct的用法

在表中,可能会包含重复值。这并不成问题,不过,有时您也许希望仅仅列出不同(distinct)的值。关键词 distinct用于返回唯一不同的值。
表a:
表b:
1.作用于单列
select distinct name from a
执行后结果如下:
2.作用于多列
示例2.1
select distinct name, id from a
执行后结果如下:
实际上是根据name和id两个字段来去重的,这种方式access和sql server同时支持。
示例2.2
select distinct xing, ming from b
返回如下结果:
返回的结果为两行,这说明distinct并非是对xing和ming两列“字符串拼接”后再去重的,而是分别作用于了xing和ming列。
3.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;
4.distinct必须放在开头
select id, distinct name from a;   --会提示错误,因为distinct必须放在开头
5.其他
distinct语句中select显示的字段只能是distinct指定的字段,其他字段是不可能出现的。例如,假如表a有“备注”列,如果想获取distinc name,以及对应的“备注”字段,想直接通过distinct是不可能实现的。
其它类似信息

推荐信息