Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CONCAT with IF condition in SQL Server

I have a table with four columns presenting {YES, NO, N/A} values. What I'd like to obtain is a column with concatenated names of those columns which present a 'YES' value separate by a double underscore.

\, A, B, C, D
1, YES, NO, YES, N/A
2, NO, YES, N/A, N/A
3, YES, NO, NO, YES

Expected result:

A__C
B
A__D

Something like:

select CONCAT(
IF(A = 'YES', 'A'),
IF(B = 'YES', 'B'),
IF(C = 'YES', 'C'),
IF(D = 'YES', 'D'))
from my_table
like image 650
Nic Avatar asked Sep 08 '26 12:09

Nic


1 Answers

Hope I understand you right, that you want a double underscore separator. This solution works without any subquery or cte processing.

select substring(
           iif(a='YES','__A','') + iif(b='YES','__B','') + 
           iif(c='YES','__C','') + iif(d='YES','__D','')
       ,3,100) 
from table1

One should know that this: substring('', 3, 100) will work using SqlServer.

like image 173
wumpz Avatar answered Sep 11 '26 12:09

wumpz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!