Row_Number()继续在Union查询中

时间:2015-04-23 11:25:54

标签: sql sql-server sql-server-2012

;WITH CTE AS
(
Select * From
        (
        SELECT ROW_NUMBER() OVER(ORDER BY StatusDate) AS SrNo, FirstName
From Tab1
  UNION ALL
   SELECT ROW_NUMBER() OVER(ORDER BY StatusDate) AS SrNo, FirstName
   From Tab2
) v
)
Select * From CTE

无论如何,我可以在Tab1中生成Row_Number()之后继续。因此,如果UNION中的第一个结果以10000结束,则UNION中的第二个表应该从10001开始

注意:我想要Row_Number()

内的Select * From

因此我无法将其改为:

;WITH CTE AS
(
Select *, ROW_NUMBER() OVER(ORDER BY StatusDate) AS SrNo From
        (
        SELECT FirstName
From Tab1
  UNION ALL
   SELECT FirstName
   From Tab2
) v
)
Select * From CTE

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:5)

由于您没有对数据进行分区,因此最大row_number应该等于行数,因此您只需将tab1中的行数添加到tab2中的行号:

;WITH CTE AS
(
SELECT * FROM
        (
        SELECT 
          ROW_NUMBER() OVER(ORDER BY StatusDate) AS SrNo, 
          FirstName 
       FROM Tab1
       UNION ALL
       SELECT 
          ROW_NUMBER() OVER(ORDER BY StatusDate) + (SELECT COUNT(*) FROM tab1) AS SrNo, 
          FirstName 
       FROM Tab2
       ) v
)
SELECT * FROM CTE

答案 1 :(得分:4)

您的要求并不完全清楚,但根据我的解释,这就是我要做的。

;WITH UnionedData AS
(
SELECT FirstName, StatusDate, 10 AS SortOrder
FROM Tab1
UNION
SELECT FirstName, StatusDate, 20 AS SortOrder
FROM Tab2
)
SELECT FirstName, ROW_NUMBER() OVER(ORDER BY SortOrder, StatusDate) AS SrNo
FROM UnionedData

答案 2 :(得分:1)

让我猜这是你真正想要的:

select FirstName
from tab1
union all
select FirstName
from tab2
where not exists (select 1 form tab1 t1 where t1.firstname = t2.firstname)

然后您可以将结果枚举为:

select FirstName, row_number() over (order by which, StatusDate) as srNo
from ((select FirstName, StatusDate, 1 as which
       from tab1
      ) union all
      (select FirstName, StatusDate, 2 as which
       from tab2
       where not exists (select 1 form tab1 t1 where t1.firstname = t2.firstname)
      )
     ) f