Showing posts with label Self JOIN. Show all posts
Showing posts with label Self JOIN. Show all posts

In SQL Query, How to Compare Across Different Rows

In SQL query, it is easy to compare values in different columns for same row. However, when compare value at column_A of Row 1 to the values at column_B of Rows 2 to 3, it would be hard. Sure, you always can write the cursor to process rows one by one. Here is a quick way: INNER JOIN this table by itself, you would get following rows: New row 1 = old row 1 and 1 New row 2 = old row 1 and 2 New row 3 = old row 1 and 3 New row 4 = old row 2 and 1 New row 5 = old row 2 and 2 New row 6 = old row 2 and 3 New row 7 = old row 3 and 1 New row 8 = old row 3 and 2 New row 9 = old row 3 and 3 Now you will be able to compare column_A and column_B at new rows 2 to 3, which is what you want. Just remember to eliminate row 1 and row 4 to 9.

Labels