手机
当前位置:查字典教程网 >编程开发 >mssql数据库 >sqlserver中distinct的用法(不重复的记录)
sqlserver中distinct的用法(不重复的记录)
摘要:下面先来看看例子:table表字段1字段2idname1a2b3c4c5b库结构大概这样,这只是一个简单的例子,实际情况会复杂得多。比如我想...

下面先来看看例子:

table表

字段1字段2

idname

1a

2b

3c

4c

5b

库结构大概这样,这只是一个简单的例子,实际情况会复杂得多。

比如我想用一条语句查询得到name不重复的所有数据,那就必须

使用distinct去掉多余的重复记录。

select distinct name from table

得到的结果是:

----------

name

a

c

好像达到效果了,可是,我想要得到的是id值呢?改一下查询语句吧:

select distinct name, id from table

结果会是:

----------

id name

1 a

2 b

3 c

4 c

5 b

distinct怎么没起作用?作用是起了的,不过他同时作用了两个

字段,也就是必须得id与name都相同的才会被排除

我们再改改查询语句:

select id, distinct name from table

很遗憾,除了错误信息你什么也得不到,distinct必须放在开头。难到不能把distinct放到where条件里?能,照样报错。

--------------------------------------------------------

下面方法可行:

select *, count(distinct name) from table group by name

结果:

id name count(distinct name)

1 a 1

2 b 1

3 c 1

最后一项是多余的,不用管就行了,目的达到

group by 必须放在 order by 和 limit之前,不然会报错

【sqlserver中distinct的用法(不重复的记录)】相关文章:

sqlserver如何从外网通过IP连接

shp2sqlserver 用法简析

sql server中的decimal或者numeric的精度问题

SQL中object_id函数的用法

SQL Server 2005中更改sa的用户名的方法

给sqlserver中的表创建索引

SQL Server 中 RAISERROR 的用法详细介绍

sql server 关于设置null的一些建议

SQL Server2008中删除重复记录的方法分享

Sql server 取当天或当月的记录

精品推荐
分类导航