I have a field in PostgreSQL of type character varying [] stored here is sector, some customers have no data, others have 1 to many sectors which ends up looking like this
**Customer** ABC
**Sector** ,Exh: Food Trade,Exh: Beverage Trade,Evt: Sporting
does any one know how I could query this out per value? to give me the unique values per customer
**Customer** ABC **sector** Exh:Food Trade,
**Customer** ABC **sector** Exh:Beverage Trade
**Customer** ABC **Sector** Evt:Sporting
Try using unnest
.
Test Data
CREATE TABLE t (customer text, sector text[]);
INSERT INTO t VALUES
('ABC',string_to_array(',Exh: Food Trade,Exh: Beverage Trade,Evt: Sporting',','));
Query
SELECT customer, unnest(sector) FROM t;
customer | unnest
----------+---------------------
ABC |
ABC | Exh: Food Trade
ABC | Exh: Beverage Trade
ABC | Evt: Sporting
(4 Zeilen)
Edit : Getting rid of empty elements using a CTE
(see comments)
WITH j AS (
SELECT customer, unnest(sector) as sector FROM t
) SELECT * FROM j WHERE sector <> '';
customer | sector
----------+---------------------
ABC | Exh: Food Trade
ABC | Exh: Beverage Trade
ABC | Evt: Sporting
(3 Zeilen)
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.