Skip to content
Advertisement

Convert multiple self JOINs to window function or subqueries (SQL)

I have a query with several self joins:

Here is a sample table where in yellow I marked the record that is within the boundaries of the where condition:

enter image description here

Here is the expected result view:

enter image description here

Basically I filter one table with several consecutive conditions and show the result as a table.

Is there a way, using window function or subquery to transform it to be faster?

Advertisement

Answer

You could improve performance by removing type conversions, adding indicies to the appropriate columns being queried so often, or by replacing a 4-table join with a PIVOT instead.

Teach yourself through examples here: https://www.sqlshack.com/dynamic-pivot-tables-in-sql-server/

Your query took 30ms to run in sql-fiddle; it only took 17ms to run the pivot w/o type-conversions in the WHERE clause, and 20-22ms to run with all the WHERE clause conversions.

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