0

我写了这个查询

SELECT 
ROW_NUMBER() OVER (ORDER BY b.s_id) as RN,
g.code as De, 
f.code as Ar
from a_c a
left join ne_a b ON b.n_a_id = a.n_a_id
left join Sh d ON d.s_id = b.s_id
left join A g ON g.a_id = a.d_a_id 
left join A f ON f.a_id = a.a_a_id 

where b.s_id = 'MHJIX'
ORDER BY b.s_id

它给了我结果

RN  De  AR

1   S   D
2   D   G
3   G   J

我想显示从 Row_Number 2 开始的结果。Row_numbers 总是可以改变的。在上面的示例中总共有 3 行,但在其他示例中可以是 5 行。如何显示从 row_number 2 开始的结果?
我怎样才能做到这一点?

4

2 回答 2

1

你需要这样的东西(CTE - 公用表表达式):

;WITH YourCTE AS
(
   SELECT 
      ROW_NUMBER() OVER (ORDER BY b.s_id) as RN,
      g.code as De, 
      f.code as Ar,
      b.s_id
   FROM a_c a
   left join ne_a b ON b.n_a_id = a.n_a_id
   left join Sh d ON d.s_id = b.s_id
   left join A g ON g.a_id = a.d_a_id 
   left join A f ON f.a_id = a.a_a_id 
   where b.s_id = 'MHJIX'
)
SELECT * FROM YourCTE
WHERE RN >= 2
ORDER BY s_id

基本上,您需要将包含ROW_NUMBER()排名函数的查询“包装”到子查询或 CTE 中,以便您可以在外部查询中引用新的“row_number”列(使用它来限制您的最终结果集)。

于 2012-04-10T14:34:07.967 回答
0

您可以按照 Marc 的建议使用 CTE,也可以使用派生表:

SELECT  b.RN,
        g.code as De, 
        f.code as Ar

FROM    a_c a
        LEFT JOIN (SELECT n_a_id, ROW_NUMBER() OVER (ORDER BY b.s_id) AS RN FROM ne_a) b ON b.n_a_id = a.n_a_id
        LEFT JOIN Sh d ON d.s_id = b.s_id
        LEFT JOIN A g ON g.a_id = a.d_a_id 
        LEFT JOIN A f ON f.a_id = a.a_a_id 

WHERE   b.s_id = 'MHJIX' AND b.RN >= 2
于 2012-04-10T14:40:24.357 回答