I want to consolidate rows with matching IDs returning from a SELECT CASE statement. I'm using pgAdmin 3
on a PG-9.3.4
database.
This is what I'm getting on pgAdmin:
And this is what I want to get:
I've tried grouping it, or joining the result to the table itself, but din't work. Any ideas?
My query code:
SELECT
CASE
WHEN t1.material LIKE '%Refuse%'
THEN t1.disposal
ELSE NULL
END AS msw_disp,
CASE
WHEN t1.material LIKE '%Met%'
THEN t1.disposal
ELSE NULL
END AS mgp_disp,
CASE
WHEN t1.material LIKE '%Paper%'
THEN t1.disposal
ELSE NULL
END AS pap_disp, t1.district
FROM dsny_net t1
Adding Aggregate
and Group by
to your current query should get the job done
SELECT Max(CASE
WHEN t1.material LIKE '%Refuse%' THEN t1.disposal
END) AS msw_disp,
Max(CASE
WHEN t1.material LIKE '%Met%' THEN t1.disposal
END) AS mgp_disp,
Max(CASE
WHEN t1.material LIKE '%Paper%' THEN t1.disposal
END) AS pap_disp,
t1.district
FROM dsny_net t1
GROUP BY t1.district
Just as alternative:
select
district,
unnest(array_agg(disposal) filter (where material like '%Refuse%')) as msw_disp,
unnest(array_agg(disposal) filter (where material like '%Met%')) as mgp_disp,
unnest(array_agg(disposal) filter (where material like '%Paper%')) as pap_disp,
from dsny_net
group by district;
Using max
will drops all other values (if any) except max.
However unnest(array_agg(disposal) filter (where material like ...)) as ...
can be replaced by max(disposal) filter (where material like ...) as..
to make query shorter.
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.