一、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、初始數據
CREATE TABLE students(
id int IDENTITY(1,1) NOT NULL,
score int NULL
) ON PRIMARY
GO
INSERT INTO students (score) VALUES (100)
INSERT INTO students (score) VALUES (100)
INSERT INTO students (score) VALUES (100)
INSERT INTO students (score) VALUES (90)
INSERT INTO students (score) VALUES (90)
INSERT INTO students (score) VALUES (85)
INSERT INTO students (score) VALUES (84)
INSERT INTO students (score) VALUES (80)
INSERT INTO students (score) VALUES (80)
INSERT INTO students (score) VALUES (75)
INSERT INTO students (score) VALUES (74)
INSERT INTO students (score) VALUES (70)
2、使用WITH TIES查詢成績排名前8的學生
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