Flatten a table

Stefan

Well-Known Member
I have a main table that has a 0:N relationship with another table. I (well really not me, but the puzzle intrigued me) want to present the first two (in reality five) results of the other table as columns of the main table. The other table can contain 0 to N rows.

Main:
Code:
id,name
1,one
2,two
3,three
4,four

Other:
Code:
main_id,id
2,A
3,A
3,B
4,A
4,B
4,C

The result should be:
Code:
1,one,null,null
2,two,A,null
3,three,A,B
4,four,A,B

The query that nearly gets the job done is the following,

Code:
SELECT m.id, m.name, o1.id as '1', o2.id as '2'
FROM pub.main AS m
LEFT JOIN pub.other AS o1 ON o1.main_id = m.id  
LEFT JOIN pub.other AS o2 ON o2.main_id = m.id AND o2.id > o1.id

But this shows double main rows:

Code:
1,one,<null>,<null>
2,two,A,<null>
3,three,A,B
3,three,B,<null>
4,four,A,B
4,four,A,C
4,four,B,C
4,four,C,<null>

I have also looked at using rowid as o2.rowid <> o1.rowid, I have added distinct and I have attempted to get TOP 1 in the query, but SQL92 is just too clunky and contorted for my brain to grasp... This is easy in ABL.

Is the above at all possible in SQL92?

The original 'concept' was created on MS SQL Server and used a cursor to run through the first records of the other table.
 
Top