Home Forums SQL Server 2012 SQL Server 2012 - T-SQL Selecting alternative value if one row(possible two) doesnt exist in reference table RE: Selecting alternative value if one row(possible two) doesnt exist in reference table

  • This may be more efficient (most people use LEFT rather than RIGHT join, so I switched it to that):

    SELECT l.value, p.productname

    FROM dbo.ProductTable p

    LEFT OUTER JOIN (

    SELECT ID, value, ROW_NUMBER() OVER(PARTITION BY ID ORDER BY flag DESC) AS row_num

    FROM dbo.lkpTable

    ) AS l ON l.ID = p.ID AND l.row_num = 1

    GROUP BY l.value, p.productname

    SQL DBA,SQL Server MVP(07, 08, 09) A socialist is someone who will give you the shirt off *someone else's* back.