Skip to content
Advertisement

Sql query for finding specific records from the table based on hierarchy

I am trying to make a SQL Query. So There are 3 sections available,Method 1,2 and 3. If A Group+SG Combination is found anywhere, we take that value based on the following hierarchy: Method3>Method2>Method1. Finally, In the output, we have That particular as Final Group and Final SG, And the value is picked up as in the above hierarchy. For example, If a Group+SG Combination is found in Method 1 and Method 2, we take the one with Method 2 as Final one. If, a Group+SG Combination is found only in Method 1 we take one with Method 1 itself as Final one. Please see the sample heresql

I created this table over here: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=e2a1534310e1ddcd5287c5bbff520d91

Advertisement

Answer

You can use CASE to decide which columns to pick.

For example:

select
  case when group3 is not null then group3
       when group2 is not null then group2
       else group1 end as final_group,
  case when group3 is not null then sg3
       when group2 is not null then sg2
       else sg1 end as final_sg,
  case when group3 is not null then value3
       when group2 is not null then value2
       else value1 end as final_value
from t
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement