Concat in If statement

Asked by At

I am trying to join two if statements together in an SQL query, but I don't seem to be having much luck.

The two statements are:

if(c.population > 100000000, Concat("Large ", c.GovernmentForm), c.GovernmentForm)

and:

if(YEAR(now())-c.IndepYear > 50, Concat("Modern ", c.GovernmentForm, c.GovernmentForm)

Both of these IF statements work separately of each other, but I need them to be combined into one (e.g. the output to be "Modern Large" & GovernmentForm, in a separate column on the output). I could do it as a function, or procedure, but they seem to be blocked on the MySQL we are using.

Any suggestions?

2 Answers

4
Gordon Linoff On Best Solutions

Put the conditional logic inside the concat() function:

concat( (case when c.population > 100000000 then 'Large ' else '' end),
        (case when YEAR(now()) - c.IndepYear > 50 then 'Modern ' else '' end),
        c.GovernmentForm
      )

This will put both, one, or neither of the prefixes depending on the conditions.

4
scaisEdge On

You could use a case when .. end

case  when c.population > 100000000  AND YEAR(now())-c.IndepYear > 50
  then  Concat("Large Modern ", c.GovernmentForm), c.GovernmentForm)
end ,
case  when c.population > 100000000 
  then  Concat("Large ", c.GovernmentForm), c.GovernmentForm), 
End 
case    when YEAR(now())-c.IndepYear > 50
  then Concat("Modern ", c.GovernmentForm, c.GovernmentForm) 
End