我不知道如何在一个表中的两列中对名称进行分组和计数。我的表的结构类似于:
+----------+---+
| Filip | 3 |
| Boris | 2 |
| Carol | 2 |
| Adam | 1 |
| Norbert | 1 |
| Patricia | 1 |
+----------+---+
我希望得到以下结果:
SELECT friend1 AS friends, friend2 AS friends, COUNT(friends) AS friedscount FROM table GROUP BY friends ORDER BY friedscount DESC
按计数排序。
我试过这样的事情:
/var/log
答案 0 :(得分:3)
首先使用UNION ALL
组合行以保留子查询中的重复项,然后计算
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
这里是Demo