A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
Here is a query for your latest requirement:
WITH secondowners AS (
SELECT ao.assetid, V.secondowner, V.ranking
FROM #asset_ownership ao
CROSS APPLY (VALUES(1, ao.secondary1_owner), (2, ao.secondary2_owner), (3, ao.secondary3_owner)) AS V(ranking, secondowner)
), secondmatches AS (
SELECT so.assetid, so.secondowner,
matchno = row_number() OVER(PARTITION BY so.assetid ORDER BY so.ranking)
FROM secondowners so
JOIN #owners o ON so.secondowner = o.owner_id
WHERE o.status = 'secondary'
), pivotseconds AS (
SELECT assetid,
MIN(CASE matchno WHEN 1 THEN secondowner END) AS sec1_match,
MIN(CASE matchno WHEN 2 THEN secondowner END) AS sec2_match,
MIN(CASE matchno WHEN 3 THEN secondowner END) AS sec3_match,
COUNT(*) AS secs_count
FROM secondmatches
GROUP BY assetid
)
SELECT ao.assetid, IIF(o.status = 'primary', o.owner_id, NULL) AS primary_owner_match,
ps.sec1_match, ps.sec2_match, ps.sec3_match,
IIF(o.status = 'secondary', o.owner_id, NULL) AS sec_match_prim,
IIF(o.status = 'primary', 1, 0), isnull(ps.secs_count, 0)
FROM #asset_ownership ao
LEFT JOIN pivotseconds ps ON ao.assetid = ps.assetid
LEFT JOIN #owners o ON ao.primary_owner = o.owner_id
ORDER BY ao.assetid
If you have larger amounts of data, it may be better to materialise one of the CTEs to a temp table.