In my PostgreSQL database I have the following schema:
CREATE TABLE slide_results (
id integer NOT NULL,
tags character varying[] DEFAULT '{}'::character varying[]
);
INSERT INTO slide_results (id, tags)
VALUES (1, '{Food, Housing}');
INSERT INTO slide_results (id, tags)
VALUES (2, '{Security, Transport}');
Now I want to have sql query that will return one additional column, this column name is domain_name
. Value of this column depends on what tags
column have. If tags
column have Food
value then domain_name
should be I need food help
, if tags include Transport
then domain_name
will have Transport help needed
. So result of the query should be
id | domain_name
1 | I need food help
2 | Transport help needed
How can I do something like this in PostgreSQL?
Here is sql fiddle with db schema:
SELECT id,CASE WHEN 'Food' = ANY(tags) THEN 'I need food help'
WHEN 'Transport' = ANY(tags) THEN 'Transport help needed'
END AS domain_name
FROM slide_results;
It seems you need a table to convert tag
to domain_name
, eg
create table tag_domain(tag text, domain_name text);
insert into tag_domain values
('Food', 'I need food help'),
('Transport', 'Transport help needed');
and use it in this way:
select *
from slide_results s
join tag_domain t on t.tag = any(s.tags)
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.