MS SQL中的DISTINCT和TOP的用法

数据库   2024-12-29 10:46   83   0  

系统先distinct运算再top运算


SELECT DISTINCT TOP (10) orderid, id, mid, wid, bought
FROM Merchandise
WHERE (cityid = 0x3034323041323036)
ORDER BY bought DESC


1.distinct:针对查询的结果去去除重复(主要针对查询的结果)

top获取前几条数据,top一般都与Order by连用(desc、asc)

distinct去除重复的数据


select distinct Sname from Student
select top 5 * from Student order by tmath desc


2.查询前百分之30%,若不是整数比向上取整


select top 35 percent * from tableScore order by desc


3.distinct要放到top前面,这样取出的结果是先将数据Distinct去重复,然后再取其中的前两行


SELECT distinct top  2  LastName FROM [dbo].[Employees] order by LastName


4.去掉重复的数据,统计count数量:


select count(distinct(xtype)) from sysobjects


5.查询前100条,并且去掉重复数据:


select distinct top 100 xtype from sysobjects 同上 select count(distinct(sysstat)) from sysobjects select distinct top 10 sysstat from sysobjects select distinct top (select count(distinct(sysstat)) from sysobjects) sysstat from sysobjects


6.如果想要在去重后选出的数据中选出前三条,则应该将distinct写在top的前面:

SELECT DISTINCT TOP 3 USERNAME,PASSWORD FROM USERS WHERE SEX='男'


7.distinct会作用在多个字段上,没有办法按一个字段去重,再取出其它的字段:


#使用disctinct获取的内容
select * from t
where x not in
(select distinct x from t2)
#取某字段非空的行
select  * from miaopai.bt_micro_user 
where aweme_count is not null
order by aweme_count desc
limit 10
#count(disinct)
select count(distinct publish_nick) from miaopai.bt_micro_user


8.去除重复数据,针对已查询出的整个结果集进行数据重复处理,而不是针对某一列。


select distinct sName from student
select distinct sName,sAge from student


9.TOP关键字获取前几条数据,一般都与order by连用


select top 5 * from TblScore order by tMath asc    --取数学成绩最低的前5个,升序排列
select top (2*2)  from TblScore order by tMath desc    --取数学成绩最高的前5个,降序排列,top后面如果是表达式,必须括起来


10. 取数学成绩最低的前%30,升序排列,百分比如果不是整数条,会向上取整(夺取一条)

select top 30 percent  * from TblScore order by tMath asc


11.其他示例:

select * from Tbstudent where stuClassId in(1,3,4)


top关键字:查询前若干条记录

select top(5) * from Tbstudent where stuClassId in(1,3,4)


查询前百分之几条记录,按百分比查询出于顶端的记录,不按四舍五入,是直接进位


select top 20 percent * from Tbstudent
select * from Tbstudent


distinct关键字:用来去除查询结构集中的重复记录


select distinct * from Tbstudent


查询所有的学生籍贯地

select distinct stuAddress from Tbstudent



博客评论
还没有人评论,赶紧抢个沙发~
发表评论
说明:请文明发言,共建和谐网络,您的个人信息不会被公开显示。