Search code examples
sqlt-sqlcase-statement

IF / Case statment in SQL


I have a column where I have 0 or 1. I like to do the following set up:

If 0 than put / use the Region_table (here I have regions like EMEA, AP,LA with finished goods only) and when it 1 then put / use the Plant_table (here I have plants with non-finished goods) data's.

enter image description here

I tried to write it in 2 different statements but it is not good:

,Case 

when [FG_NFG_Selektion]  = '0'  Then 'AC_region' 

End as 'AC_region' 

,Case

when [FG_NFG_Selektion]  = '1'  Then 'AC_plant'

End as 'AC_plant'

Solution

  • I'm not 100% clear on what you're looking for, but if you want to get data from different tables based on the value in the [FG_NFG_Selektion] field, you can do something like this:

    SELECT 
      CASE 
        WHEN [FG_NFG_Selektion] = '0' THEN r.some_col -- If 0, use value from "region" table
        WHEN [FG_NFG_Selektion] = '1' THEN p.some_col -- If 1, use value from "plant" table
      END AS new_field
    FROM MyTable t
    LEFT JOIN AC_region r ON t.pk_col = r.pk_col -- get data from "AC_region" table
    LEFT JOIN AC_plant p ON t.pk_col = p.pk_col -- get data from "AC_plant" table
    ;
    
    

    If [FG_NFG_Selektion] is a numeric field, then you should remove the single quotes: [FG_NFG_Selektion] = 0.