Row_Number()继续在Union all查询中

时间:2017-09-18 19:14:59

标签: sql union row-number union-all

如果我有3张桌子,如何获得增量唯一编号?

例如:

  • 第一个查询row_number result = 1,2,3
  • 第二个查询row_number结果= 4,5,6
  • 第3次查询row_number result = 7,8,9

我尝试了以下查询,但从中我可以获得增量到第二个表。

SELECT ROW_NUMBER() OVER(ORDER BY filename) AS SrNo,fileName FROM Tab1
UNION ALL
SELECT ROW_NUMBER() OVER(ORDER BY filename) + (SELECT COUNT(*) FROM tab1) AS 
SrNo, filename FROM Tab2
UNION ALL
SELECT ROW_NUMBER() OVER(ORDER BY filename) + (SELECT COUNT(*) FROM tab2) AS 
SrNo, filename FROM Tab3

每个表有3条记录,我想得到row_number的结果为1,2,3,4,5,6,7,8,9

1 个答案:

答案 0 :(得分:4)

使用子查询:

SELECT ROW_NUMBER() OVER (ORDER BY which, filename) as SrNo, filename
FROM (SELECT 1 as which, fileName FROM Tab1
      UNION ALL
      SELECT 2 as which, filename FROM Tab2
      UNION ALL
      SELECT 3 as which, filename FROM Tab3
     ) ttt;