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