Skip to content

Instantly share code, notes, and snippets.

@Tomamais
Created January 9, 2024 21:51
Show Gist options
  • Save Tomamais/79077bb0aa7407eb014cc2fa88359d62 to your computer and use it in GitHub Desktop.
Save Tomamais/79077bb0aa7407eb014cc2fa88359d62 to your computer and use it in GitHub Desktop.
Ranked Priority Query
WITH RankedData AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY CASE WHEN type = 'I' THEN 0 ELSE 1 END) AS TypePriority
FROM your_table_name
)
SELECT id, name, type
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY CASE WHEN type = 'E' THEN 0 ELSE 1 END) AS ETypePriority
FROM RankedData
WHERE TypePriority = 1
) AS CombinedData
WHERE TypePriority = 1 OR (TypePriority > 1 AND ETypePriority = 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment