sql 查詢記錄數(shù)結(jié)果集某個(gè)區(qū)間內(nèi)記錄
更新時(shí)間:2012年11月29日 11:03:37 作者:
sqlserver如何實(shí)現(xiàn)查詢記錄數(shù)某個(gè)區(qū)間內(nèi)記錄,本文將提供多種解決方法,需要了解的朋友可以參考下
以查詢前20到30條為例,主鍵名為id
方法一: 先正查,再反查
select top 10 * from (select top 30 * from tablename order by id asc) A order by id desc
方法二: 使用left join
select top 10 A.* from tablename A
left outer join (select top 20 * from tablename order by id asc) B
on A.id = B.id
where B.id is null
order by A.id asc
方法三: 使用not exists
select top 10 * from tablename A
where id not exists
(select top 20 * from tablename B on A.id = B.id)
方法四: 使用not in
select top 10 * from tablename
where id not in
(select top 20 id from tablename order by id asc)
order by id asc
方法五: 使用rank()
select id from
(select rank() over(order by id asc) rk, id from tablename) T
where rk between 20 and 30
中第五種方法看上去好像沒(méi)有問(wèn)題,查了下文檔,當(dāng)over()用于rank/row_number時(shí),整型列不能描述一個(gè)列,所以會(huì)產(chǎn)生非預(yù)期的效果. 待考慮下,有什么辦法可以修改為想要的結(jié)果.
方法一: 先正查,再反查
select top 10 * from (select top 30 * from tablename order by id asc) A order by id desc
方法二: 使用left join
select top 10 A.* from tablename A
left outer join (select top 20 * from tablename order by id asc) B
on A.id = B.id
where B.id is null
order by A.id asc
方法三: 使用not exists
select top 10 * from tablename A
where id not exists
(select top 20 * from tablename B on A.id = B.id)
方法四: 使用not in
select top 10 * from tablename
where id not in
(select top 20 id from tablename order by id asc)
order by id asc
方法五: 使用rank()
select id from
(select rank() over(order by id asc) rk, id from tablename) T
where rk between 20 and 30
中第五種方法看上去好像沒(méi)有問(wèn)題,查了下文檔,當(dāng)over()用于rank/row_number時(shí),整型列不能描述一個(gè)列,所以會(huì)產(chǎn)生非預(yù)期的效果. 待考慮下,有什么辦法可以修改為想要的結(jié)果.
相關(guān)文章
SQL優(yōu)化經(jīng)驗(yàn)總結(jié)
這篇文章主要內(nèi)容是SQL優(yōu)化經(jīng)驗(yàn)總結(jié),文章對(duì)SQL優(yōu)化進(jìn)行了詳細(xì)介紹,需要的朋友可以參考下2015-08-08
SQL Server 定時(shí)訪問(wèn)url激活數(shù)據(jù)同步示例
這篇文章主要介紹的是SQL Server 定時(shí)訪問(wèn)url激活數(shù)據(jù)同步的具體實(shí)現(xiàn),需要的朋友可以參考下2014-05-05
必須會(huì)的SQL語(yǔ)句(四) 數(shù)據(jù)刪除和更新
這篇文章主要介紹了sqlserver中數(shù)據(jù)刪除和更新的sql語(yǔ)句,需要的朋友可以參考下2015-01-01
sql中循環(huán)處理當(dāng)前行數(shù)據(jù)和上一行數(shù)據(jù)相加減
曾經(jīng),sql中循環(huán)處理當(dāng)前行數(shù)據(jù)和上一行數(shù)據(jù)浪費(fèi)了我不少時(shí)間,學(xué)會(huì)后才發(fā)現(xiàn)如此容易,其實(shí)學(xué)問(wèn)就是如此,難者不會(huì),會(huì)者不難。2014-08-08
SQL Server復(fù)制刪除發(fā)布時(shí)遇到錯(cuò)誤18752的問(wèn)題及解決方法
朋友反饋他無(wú)法刪除一臺(tái)SQL Server數(shù)據(jù)庫(kù)上的發(fā)布,具體情況為刪除一個(gè)SQL Server Replication的發(fā)布時(shí),遇到這樣的錯(cuò)誤問(wèn)題如何解決呢,下面小編給大家分享SQL Server復(fù)制刪除發(fā)布時(shí)遇到錯(cuò)誤18752的問(wèn)題及解決方法,感興趣的朋友一起看看吧2024-01-01
SQL Server誤區(qū)30日談 第13天 在SQL Server 2000兼容模式下不能使用DMV
對(duì)于兼容模式已經(jīng)存在了很多誤解。80的兼容模式的數(shù)據(jù)庫(kù)是否意味著能夠附加或恢復(fù)到SQL Server 2000數(shù)據(jù)庫(kù)?當(dāng)然不是2013-01-01

