I think you will need a table to hold your results. Here's how I would do it.
Keep a list of tickets processed and left to process, and a current ticket.
Keep a list of programs processed and left to process, organized by ticket #, and a current program.
While the lists are not empty,
Get the next program for the current ticket. If that's all for this ticket, then write a record to the table for that ticket and go to the next ticket and the first program. Otherwise add this program to the list for this ticket in the results.
Check that the program wasn't processed already by searching the pocessed programs list.
If it was, next. If it wasn't, get a list of all the tickets it's in with a SELECT or whatever, then add any of those tickets that haven't been processed to the list of tickets left to process.
Fortunately there is a searchable list item variable type you can use.
The List Class
This is just off the top of my head, so it could probably be refined some.
If you don't keep a list of tickets already processed, you run the risk of an infinite loop.