sql group-by包含两个表

ogq8wdun  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(397)

你们能帮我对我的简单案例进行选择查询吗:

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

对于一个表b,这是有效的:

SELECT UserID, SUM(SessionTime) AS "Total Time"
FROM TableB
GROUP BY UserID;

但我需要把用户名附加到最终结果上
谢谢您

ff29svar

ff29svar1#

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
vzgqcmou

vzgqcmou2#

您可以通过使用“联接”和“分组方式”来执行此操作:

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;

注意:这将适用于1对多关系,如您的情况。

n7taea2i

n7taea2i3#

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

在这里。我用了a表和b表

相关问题