mysql组和计数两列

时间:2018-03-07 07:16:23

标签: mysql sql count

我不知道如何在一个表中的两列中对名称进行分组和计数。我的表的结构类似于:

+----------+---+
| 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

1 个答案:

答案 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