I have two columns in a mysql database that i would like to count how many times a single name appears in both columns. The COUNT function by itself doesn't work for me as it only counts the total in one column.
MySql Columns:
+-----------------+--------------+
| Member1 | Member2 |
+-----------------+--------------+
| John | Bill |
| Bill | John |
| Joe | John |
| Bill | Joe |
| John | Steve |
+-----------------+--------------+
Desired output:
+-----------------+--------------+
| Member | Total |
+-----------------+--------------+
| John | 4 |
| Bill | 3 |
| Joe | 2 |
| Steve | 1 |
+-----------------+--------------+
Any ideas?? Thanks!
You can use the following which will unpivot your multiple columns of members into a single column using a UNION ALL
. Once it is in the single column, then you can apply the aggregate function count
:
select member, count(*) Total
from
(
select member1 as member
from yt
union all
select member2
from yt
) d
group by member
order by total desc;
See SQL Fiddle with Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With