I have a table that is setup like this:
+----+-------+-------+
| id | col1 | col2 |
+----+-------+-------+
| 1 | John | Mike |
| 2 | Mike | John |
| 3 | Marty | John |
| 4 | Walt | Marty |
| 5 | Walt | Mike |
+----+-------+-------+
I basically want to count the unique values in both col1 and col2 and display them alongside the appropriate unique value. The problem is that col1 doesn’t necessarily contain all the same names that col2 has, and vice versa. I’m looking to get it setup like this:
+-------+-------+------+
| names | col1 | col1 |
+-------+-------+------+
| John | 1 | 2 |
| Marty | 1 | 1 |
| Mike | 1 | 2 |
| Walt | 2 | NULL |
+-------+-------+------+
I can select these values independently using:
SELECT col1, count(col1) as count FROM example GROUP BY col1;
OR
SELECT col2, count(col2) as count FROM example GROUP BY col2;
But I’m having one hard time understand how I join those two counts together, especially because the value here “Walt” doesn’t appear in col2.
I’m assuming you could have more cases than you show in the data. You could have NULLs in col1, you could have names that occur only in col1 or only in col2, etc.
Explanation:
The derived table
ais a union of all names that appear in either column.Then make two more derived tables, one with each each name from col1 and the count of how many times it occurs, and then another similar derived tale for names in col2.