简体   繁体   中英

BigQuery SQL: How to use different columns in CASE expression

Input Data:

columnA  columnB
true     false
true     true
false    false
false    true

Problem Statement: From above mentioned data, I want to use different columns to get the result.

Expected Output:

columnA  columnB   result
true     false     A
true     true      B
false    false     C
false    true      C

Tried SQL Query:

SELECT
columnA, 
columnB,
CASE columnA WHEN 'true' AND columnB ='false' THEN 'A'
             WHEN 'true' AND columnB ='true' THEN 'B'
             ELSE 'C' END AS result

It seems unable to use different columns in CASE expression. Is there any solution?

Yes you can use different columns but, you need to rewrite your query

SELECT
columnA, 
columnB,
CASE WHEN columnA  = 'true' AND columnB ='false' THEN 'A'
             WHEN columnA  = 'true' AND columnB ='true' THEN 'B'
             ELSE 'C' END AS result
FROM mytable

Consider below "version"

select *,
  case (columnA, columnB) 
    when (true, false) then 'A'
    when (true, true) then 'B'
    else 'C'
  end result
from your_table    

if applied to sample data in your question - output is

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM