Skip to content
Advertisement

SQL Server : select first occurrence from two columns

(Edit: I am bound to use Visual Studio 19 and have no rights to install any other application)

I have a small SQL table with about 150k rows and 20 columns which I need to modify.

  1. I need the table to be ordered by date.
  2. I need the first occurrence of a value from two columns.
  3. Depending on if the value first occurred in column Home_Team or Away_Team, I need the column Home_Elo or Away_Elo modified to 1500.
  4. Copy into a new table.

I get the 1st part and 4th, but already have struggles getting the first occurrence from to columns – not even tried 3rd.

Sadly this not only orders by Home_Team, but also returns the first occurrence of both values.

I guess I need OR instead of AND (is that possible in SQL Server?)

Advertisement

Answer

Apply row_number() to the union of home and away teams and join to the table:

See the demo.
Results:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement