Hi, I'm having to do some table rearrangement and ran into what I would call the "set problem" which is about identifying and assigning unique sets of records with some common foreign key.

I have a table like this

ORDER CONTENTS
order_id item_id
15 2
15 3
18 2
18 5
21 2
21 3
21 8
28 2
28 5

And I need to spread the information into the following tables

SETS
set_id item_id
1 2
1 3
2 2
2 5
3 2
3 3
3 8

ORDER_SETS
order_id set_id
15 1
18 2
21 3
28 2

On the surface it looks like some sort of DISTINCT query that applies to records instead of fields, but since the values of the records (item_id in this case) can vary wildly, it is unfeasible to treat it like a transpose. Is there a relatively short SQL query or stored procedure that allows me to do that (one whose lenght or applicability doesn't depend on the number of items per set and which doesn't employs cursors)? Or do I have to get dirty with cursors or individual cases for each number of items per set?