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

Erwin Brandstetter
  • 185,527
  • 28
  • 463
  • 633
NasahT
  • 25
  • 1
  • 8

1 Answers1

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:

Erwin Brandstetter
  • 185,527
  • 28
  • 463
  • 633