Home > Database > Mysql Tutorial > How to Inner Join Two SQL Server Tables Based on Row Number?

How to Inner Join Two SQL Server Tables Based on Row Number?

Mary-Kate Olsen
Release: 2025-01-05 01:36:39
Original
834 people have browsed it

How to Inner Join Two SQL Server Tables Based on Row Number?

Inner Join on Row Number in SQL Server

Objective: Perform an inner join on two tables using their row numbers.

Scenario:

Consider two tables, A and B, with the following data:

Table A Table B
RowA Row4
RowB Row3
RowC Row2
RowD Row1

The goal is to join the tables based on their row numbers and retrieve the following output:

Table A Table B
RowA Row1
RowB Row2
RowC Row3
RowD Row4

Solution:

To perform an inner join on row numbers, utilize the ROW_NUMBER() function as follows:

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;
Copy after login

This query creates a temporary table for each input table (A and B) and assigns row numbers to each row based on the val column. The tables are then joined using the row_num column, and the results are sorted by the val column in both tables.

Additional Considerations:

  • If no specific ordering is desired, remove the ORDER BY clause from the ROW_NUMBER() function to preserve the original row order.

SQL Fiddle Demo:

[SQL Fiddle Demo](https://www.sqlfiddle.com/#!18/69540/2)

The above is the detailed content of How to Inner Join Two SQL Server Tables Based on Row Number?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template