Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Row_Number() continue in Union query

;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

Is there anyway I could continue after the Row_Number() generated in Tab1. So if 1st result in UNION ended at 10000 the 2nd table in UNION should start from 10001

Note: I want the Row_Number() as it is inside the Select * From

Thus I don't can't change it to:

;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

Any help is greatly appreciated.

like image 650
Jack Avatar asked Oct 20 '25 08:10

Jack


1 Answers

Since you're not partitioning the data the maximum row_number should be equal to the count of rows so you could simply add the count of rows in tab1 to the row number in 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
like image 57
jpw Avatar answered Oct 22 '25 22:10

jpw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!