Skip to content
Advertisement

Select from group by based on case statement

Based on a table like this I want to group by PRODID, then select a row based on a case statement. Case statement being if IND1 = 1 select row, else if IND2 = 1 select row, else select row with max DATE. If multiple indicators within a group are 1 select row with the max date from the group of indicators being 1.



Advertisement

Answer

One method uses row_number():

If you like arithmetic, this can be simplified to:

Note that one trick in putting the logic together is ensuring that the first row is used in the following situation:

This is why you can’t use order by ind1 desc, ind2 desc, date desc (which is quite tempting).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement