I have a table like this:
ID | name
=================================
1 | apple
1 | bear
2 | cactus
2 | dog
2 | apple
3 | apple
3 | dog
==================================
and I wish to get the following unique set of combinations per ID as output from an SQL query:
===================
apple | bear
apple | cactus
apple | dog
cactus | dog
===================
It’s essentially a type of transpose. Ideally, I’d like to expand this to include a count of co-occurances, like this:
===================
1 | apple | bear
1 | apple | cactus
2 | apple | dog
1 | cactus | dog
===================
but this may be above and beyond. I know I can accomplish all of the above using a stored proc; was just curious if I can do this as a query.
Any SQL will do, but MySQL would be preferred if possible.
Thanks for any and all input!
From your example, it looks like you want the first column to contain whatever
namecomes first alphabetically, so I used a<when joining the table to itself.And here’s the query in action to prove I’m not crazy.