SQL:获取分布在 3 个表中的数据


SQL: get data spread over 3 tables

我正在尝试为我维护的在线游戏获取一些统计数据。我正在寻找一个SQL语句来获得底部的结果。

有三个表:

包含团队的表,每个团队都有一个唯一的标识符。

table teams
---------------------
| teamid | teamname |
|--------|----------|
| 1      | team_a   |
| 2      | team_x   |
---------------------

包含玩家的表,每个玩家都有一个唯一的标识符,并且可以选择通过其唯一的 teamid 隶属于一个团队。

table players
--------------------------------
| playerid | teamid | username |
|----------|--------|----------|
| 1        | 1      | user_a   |
| 2        |        | user_b   |
| 3        | 2      | user_c   |
| 4        | 2      | user_d   |
| 5        | 1      | user_e   |
--------------------------------

最后是包含事件的表格。事件(持续时间以秒为单位)通过玩家 ID 与其中一名玩家相关。

table events.
-----------------------
| playerid | duration |
|----------|----------|
| 1        | 2        |
| 2        | 5        |
| 3        | 3        |
| 4        | 8        |
| 5        | 12       |
| 3        | 4        |
-----------------------

我试图得到一个总结所有团队成员持续时间的结果。

result
--------------------------
| teamid | SUM(duration) |
|--------|---------------|
| 1      | 14            | (2+12)
| 2      | 15            | (3+8+4)
--------------------------

我尝试了 UNION、WHERE IN、JOIN 和 GROUP 的几种组合,但无法正确。我正在使用PostgreSQL和PHP。谁能帮我?

只需将sumgroup by一起使用:

select t.teamid, sum(e.duration)
from team t
   join players p on t.teamid = p.teamid
   join events e on p.playerid = e.playerid
group by t.teamid

如果您需要返回所有团队,即使他们没有事件,请改用outer join

试试这个

SELECT teamid, Sum(duration), 
    AS LineItemAmount, AccountDescription
FROM teams
    JOIN teams ON teams.teamid = players.teamid
    JOIN events ON players.playersid = events.playersid
    JOIN GLAccounts ON InvoiceLineItems.AccountNo = GLAccounts.AccountNo
    GROUP BY teamid

http://www.w3computing.com/sqlserver/inner-joins-join-two-tables/