top与with ties用法


使用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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM