sqlserver中distinct的用法(不重复的记录)
时间:2024-01-12 15:27:38
下面先来看看例子:
table表
字段1 字段2
id name
1 a
2 b
3 c
4 c
5 b
库结构大概这样,这只是一个简单的例子,实际情况会复杂得多。
比如我想用一条语句查询得到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之前,不然会报错
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
win10安装Sql Server 2014图文教程
![](https://img.aspxhome.com/file/2023/2/94392_0s.png)
SQL Server2008 数据库误删除数据的恢复方法分享
![](https://img.aspxhome.com/file/2023/3/129313_0s.png)
Fuse.js模糊查询算法学习指南
Python random模块的使用示例
Web开发者的百科全书——Google DocType
玩转python爬虫之爬取糗事百科段子
![](https://img.aspxhome.com/file/2023/2/69622_0s.jpg)
Python 图形界面框架TkInter之在源码中找pack方法
![](https://img.aspxhome.com/file/2023/0/121700_0s.png)
Python AES加密模块用法分析
Python格式化文本段落之textwrap库
![](https://img.aspxhome.com/file/2023/6/92106_0s.png)
Python爬虫实例爬取网站搞笑段子
详解pandas中利用DataFrame对象的.loc[]、.iloc[]方法抽取数据
![](https://img.aspxhome.com/file/2023/2/128442_0s.png)
ASP.NET与数据库相关技巧
js+css在交互上的应用
![](https://img.aspxhome.com/file/2023/9/136219_0s.jpg)
python针对mysql数据库的连接、查询、更新、删除操作示例
Go语言同步与异步执行多个任务封装详解(Runner和RunnerAsync)
asp防范SQL注入攻击的函数
pytorch Variable与Tensor合并后 requires_grad()默认与修改方式
MYSQL之on和where的区别解读
![](https://img.aspxhome.com/file/2023/2/66612_0s.png)
Python 2种方法求某个范围内的所有素数(质数)
![](https://img.aspxhome.com/file/2023/0/117990_0s.jpg)
python数据结构输入输出及控制和异常
![](https://img.aspxhome.com/file/2023/5/111945_0s.png)