1. 程式人生 > >top與with ties用法

top與with ties用法

但是 HA order by 返回值 初始 Go center sta 用法

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