最近在學sql,遇到了這么一道題:
寫出一條Sql語句:取出表A中第31到第40記錄(SQLServer,以自動增長的ID作為主鍵,注意:ID可能不是連續的。
把所能想到的實現方法都做了一遍:
1.用集合查詢
select top 40 * from T_Testexceptselect top 30 * from T_Test
2.用NOT IN 謂詞
select top 10 * from T_Test where Idnot in(select top 30 Id from T_Test)
3.用ALL謂詞
select top 10 * from T_Test where Id>all(select top 30 Id from T_Test)
4.用MAX聚集函數
select top 10 * from T_Test where Id>(select MAX(Id) from (select top 30 Id from T_Test) as A)
這里有些問題,因為 帶有 top子句 的子查詢 沒有 order by 子句 排序的話,MAX(Id)作用的就是T_Test基本表,而不僅僅是A這個結果集,所以MAX(Id)會取到整個T_Test表的最大值,從而整個查詢沒有結果。
改正:
select top 10 * from T_Test where Id>(select MAX(Id) from (select top 30 Id from T_Test order by Id) as A)
5.用開窗函數
select Id,Name from (select *, ROW_NUMBER() over(order by Id) as num from T_Test) as Swhere S.num between 31 and 40
最后:水平有限,歡迎大家指教,共同學習進步!
新聞熱點
疑難解答