3

我有 2 个表,用户和关注。下面的表有一个名为 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 和 count 但没有用。有什么线索吗?

4

1 回答 1

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

于 2012-12-19T01:18:00.390 回答