简体   繁体   中英

Concatenate column names in sql select statement if certain condition is met

I have a SQL SELECT statement pulling 4 columns:

SELECT cmm_residence, cmm_packing, cmm_furniture, cmm_overage

These columns are simple no/yes values (0,1). I need an additional column Description to concatenate any 'Yes' values for that row.

For example: if the query returned 'Yes' for cmm_residence and cmm_furniture , the Description column should be cmm_residence,cmm_furniture .

Schema and insert statements:

 create table  mytable (cmm_residence varchar(5), cmm_packing varchar(5), cmm_furniture varchar(5), cmm_overage varchar(5));
 insert into mytable values('yes','no','no','yes');
 insert into mytable values('no','no','no','yes');
 insert into mytable values('yes','yes','no','yes');

Query:

 select cmm_residence, cmm_packing, cmm_furniture, cmm_overage,
 concat(case when cmm_residence='yes' then ' cmm_residence ,'end,
 case when cmm_packing='yes' then ' cmm_packing ,'end,
 case when cmm_furniture='yes' then ' cmm_furniture ,'end,
 case when cmm_overage='yes' then ' cmm_overage 'end)Description
 from mytable

Output:

cmm_residence cmm_packing cmm_furniture cmm_overage Description
yes no no yes cmm_residence, cmm_overage
no no no yes cmm_overage
yes yes no yes cmm_residence, cmm_packing, cmm_overage

db<fiddle here

You can use a CASE into your SELECT statement adding whatever logic you need like this:

SELECT cmm_residence, cmm_packing, cmm_furniture, cmm_overage, 
CASE
    WHEN cmm_residence = 1 THEN 'cmm_residence'
    WHEN  cmm_packing = 1  THEN 'cmm_packing'
    ELSE ''
END As 'Description' 
FROM Table

Just add as much cases with logic as you want, take into account this isn't quite performant query.

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-2024 STACKOOM.COM