whands
whands

Reputation: 21

If statement Big Query

I'm quite new user of big query with basic SQL skills. I would like to build a query that is using a conditional IF statement to add a new value in one of my field

Here is the data that i have

    YEAR  |  MONTH   | NEW YEAR
----------+----------+-------------
     2018 | April    | 
     2019 | June     | 
     2020 | May      | 

I was thinking about the following request :

Select
IF (YEAR ="2018" AND MONTH=April) THEN (NEW YEAR =2019),
IF (YEAR ="2019" AND MONTH=June) THEN (NEW YEAR =2020),
IF (YEAR ="2020" AND MONTH=May) THEN (NEW YEAR =2021)
FROM 'database'
WHERE source ='name source'

i'm trying to figure out, but impossible to set the right syntax and logic

Many thanks for your help Much appreciated !

Upvotes: 0

Views: 2533

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269543

Use a case expression:

SELECT (case when YEAR = '2018' and month = 'April' then 2019
             when YEAR = '2019' and month = 'June' then 2020
             when YEAR = '2020' and month = 'May' then 2021
        end) as NEW YEAR
FROM `database`
WHERE source = 'name source'

Upvotes: 2

Mikhail Berlyant
Mikhail Berlyant

Reputation: 172974

I feel like you forgot to mention what exactly logic you want to be implemented for your new column - but at least below fixes the issue with using IF statement

#standardSQL
SELECT 
  CASE (year, month) 
    WHEN ('2018', 'April') THEN 2019
    WHEN ('2019', 'June') THEN 2020
    WHEN ('2020', 'May') THEN 2021   
  END AS new_year
FROM 'database'
WHERE source ='name source'

Upvotes: 1

Related Questions