0

I have table with fields:

line_id, point_address:
1 | Address1
1 | Address2
2 | Address1
2 | Address3
3 | Address2
3 | Address3

For result I need table with single row for each line_id and both point_address values line_id have in separate rows:

line_id,point_address_1,point_address_2:
1 | Address1 | Address2
2 | Address1 | Address3
3 | Address2 | Address3

I'm tried to create self join but what I got is 4 result for each line_id with all combinations of point_address fields. What is the best way to get single result

1 Answer 1

1

Assuming there are only ever two addresses per distinct line_id, you can work around by forcing an order on point_address in the result table:

SELECT
    l1.line_id, l1.point_address AS point_address1, 
        l2.point_address AS point_address2
    FROM line_address l1 JOIN line_Address l2 ON l1.line_id = l2.line_id
    WHERE l1.point_address < l2.point_address;

line_id     point_address1  point_address2
----------  --------------  --------------
1           Address1        Address2      
2           Address1        Address3      
3           Address2        Address3   

Note that this only works under the above assumption, hence if we add

INSERT INTO line_address (line_id, point_address) VALUES (3, 'Address4');

the select yields

line_id     point_address1  point_address2
----------  --------------  --------------
1           Address1        Address2      
2           Address1        Address3      
3           Address2        Address3      
3           Address2        Address4      
3           Address3        Address4 

Relational algebra does not take it kindly when you try to make rows into columns and vice versa.

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

1 Comment

Yes, I have only two addresses per distinct line_id and this forcing an order on point_address worked great.

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.