2011-03-15 53 views
0
sno acco_no amount 

1 50001  5000 
2 50002  4000 
3 50001  2500 
4 50002  3100 
5 50002  3400 
6 50001  1500 

我想50001的最後2條記錄逐一。如何取1 1

select sno, acco_no, amount 
from table 
where acco_no = 50001 
order by tno desc fetch first 2 rows only 

sno acco_no amount 
    6  50001  1500 
    3 50001  2500 

,但我想通過1個記錄像下面

1)第一步

select sno, acco_no, amount 
from table 
where acco_no = 50001 

sno acco_no amount 
    6  50001  1500 

2)第二步

select sno, acco_no, amount 
from table 
where acco_no = 50001 

sno acco_no amount 
    3  50001  2500 

注意獲取1:不應該刪除任何記錄

+4

首先:** **爲什麼二:!?!?!爲**什麼數據庫**? – 2011-03-15 11:31:15

+2

這聽起來像是你試圖在數據層中放置業務邏輯/工作流程,這並不一定是壞事,但在這種情況下,如果你可以在應用程序級別通過記錄集,我認爲你會更容易。 – Thyamine 2011-03-15 11:39:35

回答

1

你可以簡單地使用LIMIT/OFFSET的那些東西,取決於您使用的數據庫... 對Postgres的:http://www.postgresql.org/docs/8.1/static/queries-limit.html

MySQL的限制,關鍵字有2個參數的限制和偏移定義

select sno, acco_no, amount 
from table 
where acco_no = 50001 LIMIT 0,1 

sno acco_no amount 
    3  50001  2500 

第二

select sno, acco_no, amount 
from table 
where acco_no = 50001 LIMIT 1,1 

sno acco_no amount 
    3  50001  2500