[英]Build comma-separated list of qualifying column names
I have this table:我有这张桌子:
CREATE TABLE fruits (
id int,
apple varchar(50),
pear varchar(50),
orange varchar(50),
grapes varchar(50),
banana varchar(500)
)
INSERT INTO fruits(id, apple, pear, orange, grapes, banana)
VALUES (51,0,1,0,0,0), (52,0,1,0,0,1), (53,1,0,1,0,1),(54,1,0,0,0,1)
So that:以便:
SELECT *
FROM fruits
id apple pear orange grapes banana
------------------------------------------
51 0 1 0 0 0
52 0 1 0 0 1
53 1 0 1 0 1
54 1 0 0 0 1
I want to select the column names for which the value is 1
, into a tab-separated csv file.我想将 select 值为1
的列名放入制表符分隔的 csv 文件中。
Intended file format:预期文件格式:
51 pear
52 pear,banana
53 apple,orange,banana
54 apple,banana
A couple of CASE
expressions, wrapped in concat_ws()
to deal with null values properly:几个CASE
表达式,包裹在concat_ws()
中以正确处理 null 值:
SELECT id
, concat_ws( ', '
, CASE WHEN apple = '1' THEN 'apple' END
, CASE WHEN pear = '1' THEN 'pear' END
, CASE WHEN orange = '1' THEN 'orange' END
, CASE WHEN banana = '1' THEN 'banana' END) AS fruit_list
FROM fruits;
See:看:
Of course, your columns should rather be boolean
instead of varchar
to begin with.当然,您的列应该是boolean
而不是varchar
开头。 Then it could be just:那么它可能只是:
CASE WHEN apple THEN 'apple' END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.