如何选择内连接的最后一行中的第二行?

时间:2017-12-15 01:48:29

标签: sql-server

所有我是SQL服务器查询的初学者我练习查询,我很难选择最后一行这是我的查询代码。



select
	top 1 * 
from (select
			top 2 * 
		from MemberSample ms 
			inner join sample1 s1
		on s1.MemberId = ms.MemberId
			inner join sample2 s2
		on s2.MemberId = s1.MemberId
			inner join sample3 s3
		on s3.MemberId = s2.MemberId
		where ms.MemberId = '001' and s1.creationdate = s3.transactiondate order by s2.[tran_Number] desc)x 
order by s2.[tran_Number]




1 个答案:

答案 0 :(得分:1)

只需使用ROW_NUMBER,然后保留第二条记录,记录您当前使用的内部顺序。

SELECT *
FROM
(
    SELECT
        ms.MemberId,
        ms.col1,
        s1.col2,
        s2.col3,
        ROW_NUMBER() OVER (ORDER BY s2.[tran_Number] DESC) rn
    FROM MemberSample ms 
    INNER JOIN sample1 s1
        ON s1.MemberId = ms.MemberId
    INNER JOIN sample2 s2
       ON s2.MemberId = s1.MemberId
    INNER JOIN sample3 s3
        ON s3.MemberId = s2.MemberId
    WHERE
        ms.MemberId = '001' AND
        s1.creationdate = s3.transactiondate
) t
where t.rn = 2;

我猜测您要选择的列,但不要使用SELECT *,而只是列出您想要的列。

请注意,如果关系可能是一个问题,那么我们可能需要重新考虑这一点,而是使用排名函数。