There's probably an easier way to do this, as there are a ton of experts here.
I would instantiate a new class for wpdb and use it (calling wp_query('SQL HERE'); as the object to reference the contents.
Then just process the object with PHP. I know this is vauge, but I didn't really want to write the SQL for you. That's how you learn, my friend!