I have no idea ho to group and count names in two columns in one table. Structure of my table is something like:
+------+-------------------+
| user | friend1 | friend2 |
+------+---------+---------+
|user1 | Adam | Filip |
|user2 | Boris | Norbert |
|user3 | Filip | Carol |
|user4 | Carol | Filip |
|user5 | Boris | Patricia|
+------+---------+---------+
And I would like to get results as:
+----------+---+
| Filip | 3 |
| Boris | 2 |
| Carol | 2 |
| Adam | 1 |
| Norbert | 1 |
| Patricia | 1 |
+----------+---+
It's ordered by count.
I tried something like this:
SELECT friend1 AS friends, friend2 AS friends, COUNT(friends) AS friedscount FROM table GROUP BY friends ORDER BY friedscount DESC
combine the rows first using UNION ALL
to preserve duplicates inside a subquery then count
SELECT friend, COUNT(*) friedscount
FROM
(
SELECT friend1 AS friend FROM TableName UNION ALL
SELECT friend2 AS friend FROM TableName
) a
GROUP BY friend
ORDER BY friedscount DESC
Here's a Demo
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.