首页 > 其他 > 详细

top与with ties用法

时间:2018-05-03 12:39:14      阅读:261      评论:0      收藏:0      [点我收藏+]

使用top中把与最后一条记录值相同的数据也放入列表中

一、SQL SERVER中使用WITH TIES的用途

 

with ties一般是和Top , order by相结合使用的,会查询出最后一条数据额外的返回值(如果按照order by 参数排序TOP n返回了前面n个记录,但是n+1…n+k条记录和排序后的第n条记录的参数值(order by 后面的参数)相同,则n+1、…、n+k也返回。n+1、…、n+k就是额外的返回值)。

 

 

 

二、通过实例说明WITH TIES

 

 

1、初始数据

 

[sql] view plain copy
 
  1. CREATE TABLE students(  
  2.     id int IDENTITY(1,1) NOT NULL,  
  3.     score int NULL  
  4. ON PRIMARY  
  5. GO  
  6. INSERT INTO students (score) VALUES (100)  
  7. INSERT INTO students (score) VALUES (100)  
  8. INSERT INTO students (score) VALUES (100)  
  9. INSERT INTO students (score) VALUES (90)  
  10. INSERT INTO students (score) VALUES (90)  
  11. INSERT INTO students (score) VALUES (85)  
  12. INSERT INTO students (score) VALUES (84)  
  13. INSERT INTO students (score) VALUES (80)  
  14. INSERT INTO students (score) VALUES (80)  
  15. INSERT INTO students (score) VALUES (75)  
  16. INSERT INTO students (score) VALUES (74)  
  17. INSERT INTO students (score) VALUES (70)  

 

 

2、使用WITH TIES查询成绩排名前8的学生

 

 

 

[sql] view plain copy
 
  1. SELECT TOP 8 WITH TIES * FROM students ORDER BY score DESC  

 

 

结果

 

技术分享图片

 

 

说明

 

上面的这条查询将会返回9行,原因在于第9行中的score值都与第8行相同。

 

 

参考资料:SQL SERVER中WITH TIES的用法  http://www.studyofnet.com/news/1227.html

 

top与with ties用法

原文:https://www.cnblogs.com/gered/p/8984706.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!