用group_concat和count计算mysql行到列?

时间:2012-12-19 01:14:35

标签: mysql count group-concat

我有2个表,用户和以下。 table follow有一个名为status的列。我想计算每个用户按状态分组的次数。

以下查询返回每个用户的每种状态类型的记录。

SELECT users.name as user_name, f.status, count(f.id) 
FROM users
JOIN application_follows f ON f.user_id = users.id
GROUP BY users.id, f.status
ORDER BY users.id

返回类似的内容:

user_name     status     count

mike          new         10
mike          old         5
tom           new         8
tom           old         9

但是我想要更友好的东西:

user_name     new    old

mike          10      5
tom           8       9

尝试使用group_concat并计数但没有工作。有线索吗?

1 个答案:

答案 0 :(得分:0)

SELECT  user_name, 
        MAX(CASE WHEN status = 'new' THEN totalFollowers ELSE NULL END) `NEW`,
        MAX(CASE WHEN status = 'old' THEN totalFollowers ELSE NULL END) `OLD`
FROM
    (
        SELECT  users.name as user_name, 
                f.status, 
                count(f.id) totalFollowers 
        FROM    users
                LEFT JOIN application_follows f 
                    ON f.user_id = users.id
        GROUP BY users.id, f.status
    ) derivedTable
GROUP BY user_name

<击>

<击>

或者(不确定这个

SELECT  users.name as user_name, 
        MAX(CASE WHEN f.status = 'new' THEN count(f.id) ELSE NULL END) `NEW`, 
        MAX(CASE WHEN f.status = 'old' THEN count(f.id) ELSE NULL END) `OLD`
FROM    users
        LEFT JOIN application_follows f 
            ON f.user_id = users.id
GROUP BY users.id, f.status

<击>