0

How can I transpose these values to take this table:

enter image description here

And make it look like this:

enter image description here

There's no Pivot function that I can use in postgresql and every time I try the crosstab function, I keep getting an error in my code. Let's pretend that my table is called select * from TAttributes

1

2 Answers 2

1

Use conditional aggregation, which in Postgres means filter:

select id,
       max(attributenumber) filter (where attributeid = 2000),
       max(attributenumber) filter (where attributeid = 2001),
       max(attributenumber) filter (where attributeid = 2002),
       max(attributenumber) filter (where attributeid = 2003)
from t
group by id;

Here is a db<>fiddle.

Sign up to request clarification or add additional context in comments.

4 Comments

unfortunately, this just gives me null values throughout
@oaker . . . I added a db<>fiddle. The code works and answers your question.
Looks like it worked! Can I do the same with dates? for example, max(attributedate) filter (where attributeid = 2007), etc. I'm trying that out but it's giving me an ERROR: sytanx error at or near "max"
Yes, you can use dates. MAX() works on pretty much all data types.
0

Try this:

SELECT id,  
    MAX((SELECT attributenumber FROM public.t WHERE ext_t.id = id AND ext_t.attribuiteid = attribuiteid AND attribuiteid = 2000)) AS '2000',
    MAX((SELECT attributenumber FROM public.t WHERE ext_t.id = id AND ext_t.attribuiteid = attribuiteid AND attribuiteid = 2001)) AS '2001',
    MAX((SELECT attributenumber FROM public.t WHERE ext_t.id = id AND ext_t.attribuiteid = attribuiteid AND attribuiteid = 2002)) AS '2002',
    MAX((SELECT attributenumber FROM public.t WHERE ext_t.id = id AND ext_t.attribuiteid = attribuiteid AND attribuiteid = 2003)) AS '2003' 
FROM public.t ext_t GROUP BY id

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.