I am trying to produce a report that effectively has a pivot table in it. Other than writing a few sql statements, and doing it long hand through code (Excel / VBA) and loops, I can't seem to get anywhere trying to build an all-encompassing sql statement.
I have listed example tables below, and an example of what I would like to output at the end.
Basically I need to find which contact is in which group, and display either the total occurrences or a true false as to whether they are in the group or not.
So, for all groups in the groups table list all contacts out with an indication (count etc) of them having the group in the contact_groups table.
Is this even possible with a single statement, or would I be better sequentially running through the records. Obviously this could produce a ridiculous amount of sql calls.
Tables:
groups
-------------------
| key_id | group |
-------------------
| 1 | group1 |
| 2 | group2 |
| 3 | group3 |
| 4 | group4 |
| 5 | group5 |
contacts
------------------------------------------------
| key_id | account_code | first_name | surname |
------------------------------------------------
| 1 | abc001 | John | Smith |
| 2 | abc001 | Philip | Doe |
| 3 | abc002 | Peter | Thomas |
contact_groups
---------------------------------------------------
| key_id | contact_id | group_code | account_code |
---------------------------------------------------
| 1 | 1 | group1 | abc001 |
| 2 | 1 | group2 | abc001 |
| 3 | 2 | group1 | abc001 |
| 4 | 3 | group2 | abc002 |
Output Req'd
-----------------------------------------------------------------------
| name | account | group1 | group2 | group3 | group4 | group5 |
-----------------------------------------------------------------------
| John Smith | abc001 | 1 | 1 | | | |
| Philip Doe | abc001 | 1 | | | | |
| Peter Thomas | abc002 | | 1 | | | |
Sorry for the size of the post, I just wanted to make it clear what tables I was working with.
Any help would be appreciated.