0

This is the first time i used transpose so i dont know if what i want is possible or not

this is my query

SELECT * 
FROM crosstab( 
    'select p.name, a.attributekey, a.attributevalue
    from productz p 
    join attribute a on a.itemid=p.id
    order by p.name, a.attributekey') 
     AS final_result(name varchar, interface varchar, negativemargin varchar,parity varchar);
select p.name, a.attributekey, a.attributevalue
    from productz p 
    join attribute a on a.itemid=p.id
order by p.name, a.attributekey;

here's the link http://rextester.com/IQNSY51011

but the output is different than what i want, because productz 1 have two row and the productz 2 have 3 row

name      interface negativemargin parity
dufan     true      true           NULL
waterboom android   true           false

the output i want is this below without insert interface,Null to database

name      interface negativemargin parity
dufan     NULL      true           true
waterboom android   true           false

Note: please click "run it" after opening the link

1 Answer 1

1

Solution to your problem:

SELECT * 
FROM crosstab( 
    'select p.name, a.attributekey, a.attributevalue
    from productz p 
    join attribute a on a.itemid=p.id
    order by p.name, a.attributekey',
    'SELECT DISTINCT attributekey FROM attribute ORDER BY 1') 
     AS final_result(name varchar, interface varchar, negativemargin varchar,parity varchar);

LINK: http://rextester.com/OPNK82802

Use crosstab(text, text) with 2 input parameters. The second parameter can be any query that returns one row per attribute matching the order of the column definition at the end.

What is the problem with CROSSTAB(text) i.e. crosstab with 1 parameter?

The main limitation of the single-parameter form of crosstab is that it treats all values in a group alike, inserting each value into the first available column. If you want the value columns to correspond to specific categories of data, and some groups might not have data for some of the categories, that doesn't work well. The two-parameter form of crosstab handles this case by providing an explicit list of the categories corresponding to the output columns.

For more info on crosstab follow the below link:

https://www.postgresql.org/docs/9.2/static/tablefunc.html

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

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.