[Irving]SQL去重复-DISTINCT用法

时间:2023-03-08 23:26:29
[Irving]SQL去重复-DISTINCT用法

在表中,可能会包含重复值。这并不成问题,不过,有时您也许希望仅仅列出不同(distinct)的值。关键词 distinct用于返回唯一不同的值。

表A:
[Irving]SQL去重复-DISTINCT用法

示例1

select distinct name from A

执行后结果如下:
[Irving]SQL去重复-DISTINCT用法

示例2

select distinct name, id from A

执行后结果如下:
[Irving]SQL去重复-DISTINCT用法

实际上是根据“name+id”来去重

示例3:统计

select count(distinct name) from A;	  --表中name去重后的数目, SQL Server支持,而Access不支持
select count(distinct name, id) from A; --SQL Server和Access都不支持

示例4

select id, distinct name from A;   --会提示错误,因为distinct必须放在开头

其他

distinct语句中select显示的字段只能是distinct指定的字段,其他字段是不可能出现的。例如,假如表A有“备注”列,如果想获取distinc name,以及对应的“备注”字段,想直接通过distinct是不可能实现的。