Share via

T-SQL optimization needed

Naomi Nosonovsky 8,906 Reputation points
2025-08-19T13:08:32.61+00:00

Hi everybody,

I have the following code which I have commented:

      --CASE
           --    WHEN Status = 'Termed' THEN
           --        CASE
           --            WHEN ProviderType IN ( 'Group, Solo' ) THEN
           --                NULL
           --            WHEN ProviderType = 'Rendering' THEN
           --            (
           --                SELECT TOP (1)
           --                       dt
           --                FROM
           --                (
           --                    SELECT LAST_VALUE([OHCS Term Date]) OVER (PARTITION BY npi, tin_number ORDER BY [cte].[OHCS Term Date]) AS dt
           --                    FROM cte a
           --                    WHERE a.npi = cte.npi
           --                          AND a.tin_number = cte.tin_number
           --                    UNION ALL
           --                    SELECT MAX(hn.load_date)
           --                    FROM rv.hub_npi hn
           --                    WHERE NOT EXISTS
           --                    (
           --                        SELECT 1
           --                        FROM stg.stg_facets_full f
           --                        WHERE f.npi_hk = hn.npi_hk
           --                              AND f.primary_contracted_relationship = 'Clinician Only'
           --                    )
           --                          AND hn.source = 'FACETS'
           --                ) subselect
           --                ORDER BY dt DESC
           --            )
           --        END
           --END AS [SG Latest Term Date]

With this code uncommented I had to kill the query after 8 minutes. With this code commented the query executed in 7 seconds. Do you have suggestions as how I may re-write it to improve performance.

The business rules said: "If record Status = Termed: Group or Solo: Copy ""OHCS Term Date"" and store here. Rendering: Store latest term date from OHCS daily file or date NPI disappeared from OHBS daily file. Join on NP. "

SQL Server | SQL Server Transact-SQL

Answer accepted by question author

  1. Joerg 62 196 Reputation points
    2025-08-19T18:26:53.08+00:00

    Hi,

    change your subselects in the query first in CTE or in temp table, and then join the CTE or temp table in your final query.

    Regards Jörg


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.