[英]SQL group by 2 fields
我得到那張桌子:
id, user_a, user_b, score
1, 3, 7, 19
2, 8, 3, 20
3, 3, 2, 10
4, 7, 6, 2
5, 3, 6, 7
我實現了用計算每個用戶的匹配數:
select user, count(*)
from
(
select user_a as user from tablename
union all
select user_b from tablename
) dt
group by user
我現在想從usertable添加用戶電子郵件:
COUNT(*), user, email
4, 3, user3@mail.com
2, 7, user7@mail.com
1, 8, user8@mail.com
1, 2, user2@mail.com
2, 6, user6@mail.com
我已經試過了:
SELECT user, count(*)
FROM (
SELECT user_a AS user, ut.email
FROM tablename
UNION ALL
SELECT user_b
FROM tablename
) dt
WHERE user IS NOT NULL
LEFT JOIN usertable ut ON ut.id = user
GROUP BY user
但存在語法錯誤:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN usertable ut ON ut.id = user
GROUP BY user'
任何想法 ?
在派生表中執行UNION ALL
,以獲取一列用戶。 GROUP BY
結果。
select user, count(*)
from
(
select user_a as user from tablename
union all
select user_b from tablename
) dt
group by user
回答更新的問題:
SELECT dt.user, ut.email, count(*)
FROM
(
SELECT user_a AS user FROM tablename
UNION ALL
SELECT user_b FROM tablename
) dt
LEFT JOIN usertable ut ON ut.id = dt.user
GROUP BY dt.user, ut.email
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.