Joining Tables on Row Number in SQL Server
In SQL Server 2008, you can perform an inner join on row number using the ROW_NUMBER() function. This function assigns a unique sequential number to each row in a table, based on an optional sorting specification.
Query for Vertically Ordering Joined Rows:
To join tables A and B on their row numbers and maintain the vertical ordering of the rows, use the following query:
SELECT A.val, B.val FROM ( SELECT val, ROW_NUMBER() OVER (ORDER BY val) AS row_num FROM A ) AS A JOIN ( SELECT val, ROW_NUMBER() OVER (ORDER BY val) AS row_num FROM B ) AS B ON A.row_num = B.row_num ORDER BY A.val, B.val;
Query for Horizontally Ordering Joined Rows:
If you want to join the rows horizontally, without sorting, replace the ORDER BY clauses with the PARTITION BY clause:
SELECT A.val, B.val FROM ( SELECT val, ROW_NUMBER() OVER (PARTITION BY 1) AS row_num FROM A ) AS A JOIN ( SELECT val, ROW_NUMBER() OVER (PARTITION BY 1) AS row_num FROM B ) AS B ON A.row_num = B.row_num;
Example:
Using the sample tables A and B provided, the first query will produce the following output:
RowA Row1 RowB Row2 RowC Row3 RowD Row4
The second query will produce this output, representing a horizontal join:
RowA Row4 RowB Row3 RowC Row2 RowD Row1
The above is the detailed content of How Can I Join SQL Server Tables Based on Row Number and Control Ordering?. For more information, please follow other related articles on the PHP Chinese website!