Skip to content
Advertisement

SQL Server select query based on logic

I have the below table :

ID  Package
1   T
1   E
1   B
1   F
2   E
3   E
3   F
4   F
5   B
5   F

I need the below output table :

ID  Package
1   T
2   E
3   E
4   F
5   B

Priority list for the packages : T, E, B, F . Basically the logic should be as below :

  1. If multiple entries of ID is there then select the packages based on priority list
  2. If single entry, then pick it as such

Advertisement

Answer

We can use ROW_NUMBER here:

WITH cte AS (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY ID
                                   ORDER BY CASE Package WHEN 'T' THEN 1
                                                         WHEN 'E' THEN 2
                                                         WHEN 'B' THEN 3
                                                         WHEN 'F' THEN 4 END) rn
    FROM yourTable t
)

SELECT ID, Package
FROM cte
WHERE rn = 1;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement