1

I have a a single row with age buckets as column names. I want them all in one column with their count or sum whatever I end up doing. I have quite a few buckets but for the sake of this example I've kept it simple. Please see the attached picture of the data and the outcome that is needed.

enter image description here

1
  • 2
    Please provide data as text. Best as usable test case. Never as image. And always your version of Postgres. Aug 6, 2022 at 0:52

1 Answer 1

1

A VALUES expression in a LATERAL join is among the most elegant solutions:

SELECT x.*
FROM   tbl t
CROSS  JOIN LATERAL (
   VALUES
     ('age5' , t.age5)
   , ('age10', t.age10)
   , ('age15', t.age15)
   , ('age20', t.age20)
   ) x (bucket_name, bucket_value);

See:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.