SQL GROUP BY 涉及两个表
SQL GROUP BY with two tables involved
你们能帮我SELECT查询我的简单案例吗:
Table A:
UserID UserName
10 John
11 Mike
12 Matt
Table B:
SessionID UserID SessionTime
124 10 20
123 10 122
42 10 30
324 11 55
534 11 42
344 12 19
653 12 32
我需要这个结果:
Result Table:
UserName UserID TotalTime
John 10 172
Mike 11 97
Matt 12 51
对于一个 Table B 这有效:
SELECT UserID, SUM(SessionTime) AS "Total Time"
FROM TableB
GROUP BY UserID;
但我需要将用户名附加到最终结果
谢谢
您可以通过使用加入和分组来做到这一点:
select a.UserId, a.UserName, sum(b.SessionTime) as TotalTime
from tableA a
left join tableB b on a.UserId = b.UserId
group by a.UserId, a.UserName;
注意:这适用于您的情况下的一对多关系。
SELECT TableA.Username, TableA.User_ID, SUM(SessionTime) INNER JOIN
TableB ON TableA.User_ID = TableB.User_ID GROUP BY TableA.Username,
TableA.User_ID
SELECT a.UserName as "UserName"
,a.UserID as "UserID"
,sum(b.SessionTime) as "TotalTime"
FROM a LEFT JOIN b
ON a.UserID = b.UserID GROUP BY a.UserID
这里。我用了 TABLE a 和 Table b
你们能帮我SELECT查询我的简单案例吗:
Table A:
UserID UserName
10 John
11 Mike
12 Matt
Table B:
SessionID UserID SessionTime
124 10 20
123 10 122
42 10 30
324 11 55
534 11 42
344 12 19
653 12 32
我需要这个结果:
Result Table:
UserName UserID TotalTime
John 10 172
Mike 11 97
Matt 12 51
对于一个 Table B 这有效:
SELECT UserID, SUM(SessionTime) AS "Total Time"
FROM TableB
GROUP BY UserID;
但我需要将用户名附加到最终结果
谢谢
您可以通过使用加入和分组来做到这一点:
select a.UserId, a.UserName, sum(b.SessionTime) as TotalTime
from tableA a
left join tableB b on a.UserId = b.UserId
group by a.UserId, a.UserName;
注意:这适用于您的情况下的一对多关系。
SELECT TableA.Username, TableA.User_ID, SUM(SessionTime) INNER JOIN
TableB ON TableA.User_ID = TableB.User_ID GROUP BY TableA.Username,
TableA.User_ID
SELECT a.UserName as "UserName"
,a.UserID as "UserID"
,sum(b.SessionTime) as "TotalTime"
FROM a LEFT JOIN b
ON a.UserID = b.UserID GROUP BY a.UserID
这里。我用了 TABLE a 和 Table b