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;
If a single name appears in 1 columns 2 times and more, above sql result will be wrong. Try it with "distinct" statement in subquery.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.