I have an SQL statement that yeilds something like this:
Amounts
$101.45
$1000.56
$20978.44
$2.98
The SQL that got me this is:
select CHANGE_EFFECTIVE_AMOUNT
from V_Rpt
where ACCOUNT_NUMBER = '100'
and CHANGE_TYPE_CODE = 2
order by TRAN_SEQUENCE_NUMBER desc
How can I structure my statement so that it only returns the second value in this column? Basically, something like "select the 2nd in a column from..." The value will change all the time but it will always be the value after the top one.
I am using Microsoft SQL Server 2008 R2, in case it matters. And, this will eventually go into MS Access 2007 as a pass-through query.
You could achieve this using the ROW_NUMBER()
function.
;WITH CTE AS(
SELECT
CHANGE_EFFECTIVE_AMOUNT,
RN = ROW_NUMBER() OVER(ORDER BY TRAN_SEQUENCE_NUMBER DESC)
FROM V_Rpt
WHERE
ACCOUNT_NUMBER = '100'
AND CHANGE_TYPE_CODE = 2
)
SELECT CHANGE_EFFECTIVE_AMOUNT
FROM CTE
WHERE RN = 2
This will return nothing if your query has only 1 row.
Using a SUBQUERY:
SELECT
t.CHANGE_EFFECTIVE_AMOUNT
FROM(
SELECT
CHANGE_EFFECTIVE_AMOUNT,
RN = ROW_NUMBER() OVER(ORDER BY TRAN_SEQUENCE_NUMBER DESC)
FROM V_Rpt
WHERE
ACCOUNT_NUMBER = '100'
AND CHANGE_TYPE_CODE = 2
)t
WHERE t.RN = 2
Try to add this OFFSET 1 ROW FETCH NEXT 1 ROW ONLY
to your query.
select CHANGE_EFFECTIVE_AMOUNT
from V_Rpt
where ACCOUNT_NUMBER = '100'
and CHANGE_TYPE_CODE = 2
order by TRAN_SEQUENCE_NUMBER desc OFFSET 1 ROW
FETCH NEXT 1 ROW ONLY;
OFFSET
skip 1 row and return only the next row from the result set.
select * from table_name limit 1,1
对于limit x,y
x
是开始行和的索引y
是行数。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.