[英]mysql row to column with group_concat and count?
我有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並計數但沒有工作。 有線索嗎?
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.