Reputation: 7
I have two tables in my Databasei.e Roll Header and Roll Body. Data in tables is saved as follow
Roll Header Roll Body
id Name Color id name roll_header_id
1 abc black 1 fgh 1
2 cde white 2 hnj 1
3 asd 1
4 weq 2
5 asd 2
6 iuo 2
Now I want the result of both tables in following manner
RESULT
id name roll_header_id id Name Color
1 fgh 1 1 abc black
2 hnj 1 null null null
3 asd 1 null null null
4 weq 2 2 cde white
5 asd 2 null null null
6 iuo 2 null null null
I have tried join unions and everything but still no success
Upvotes: 0
Views: 26
Reputation: 42611
SELECT body.id,
body.name,
body.roll_header_id,
CASE WHEN body.id = body_header.id
THEN header.id
END header_id,
CASE WHEN body.id = body_header.id
THEN header.name
END header_name,
CASE WHEN body.id = body_header.id
THEN header.color
END header_color
FROM body
JOIN header on body.roll_header_id = header.id
JOIN (SELECT MIN(id) id, roll_header_id
FROM body
GROUP BY roll_header_id) body_header ON body_header.roll_header_id = body.roll_header_id
ORDER BY body.id;
Upvotes: 1