I want to make a query in MySQL or postgres that will be generated from 4 tables.
Please see the following tables.
I want postgres or sql query for matrix table that is defined below.
How can I achieve this using SQL?
Thank you a lot in advance.
table: Targets
+----+-------------+
| id | name |
+----+-------------+
| 1 | 9999999991 |
| 2 | 9999999992 |
| 3 | 9999999993 |
| 4 | 9999999994 |
| 5 | 9999999995 |
| 6 | 9999999996 |
| 7 | 9999999997 |
| 8 | 9999999998 |
+----+-------------+
table: Target_groups
+----+-------------+
| id | name |
+----+-------------+
| 1 | Group 1 |
| 2 | Group 2 |
| 3 | Group 3 |
| 4 | Group 4 |
+----+-------------+
table: Target_groups_map
+----+-----------+--------------+
| id |targets | target_groups|
+----+-----------+--------------+
| 1 | 9999999991| 1 |
| 2 | 9999999992| 1 |
| 3 | 9999999993| 2 |
| 4 | 9999999994| 2 |
| 5 | 9999999995| 3 |
| 6 | 9999999996| 3 |
| 6 | 9999999997| 4 |
| 6 | 9999999998| 4 |
+----+-----------+--------------+
table: Call_details
+----+-----------+--------------+
| id | caller | called |
+----+-----------+--------------+
| 1 | 9999999995| 9999999996 |
| 2 | 9999999992| 9999999998 |
| 3 | 9999999993| 9999999998 |
| 4 | 9999999994| 9999999991 |
| 5 | 9999999995| 9999999998 |
| 6 | 9999999996| 9999999992 |
| 6 | 9999999991| 9999999993 |
| 6 | 9999999992| 9999999998 |
+----+-----------+--------------+
Matrix table that I want
+--------+--------+--------+--------+--------+
| | Group 1| Group 2| Group 3| Group 4|
+--------+--------+--------+--------+--------+
| Group 1| - | 1 | - | 2 |
| Group 2| 1 | - | - | 1 |
| Group 3| 1 | - | 1 | 1 |
| Group 4| - | - | - | - |
+--------+--------+--------+--------+--------+
JOINs? Or with the "pivoting"? Or both?