计算表中组的总和并加入其他表sql

时间:2017-04-05 08:51:32

标签: sql

我在sql中有两个表。

table_team

t_id  team_name
 1      ABC
 2      XYZ
 3      PQR

我有另一个table_player

p_id t_id   player_name  payment
 10    1           Sam          1000
 20    1           jon           500
 30    2           will          680
 40    1           bob           700
 50    3           rob           890

我希望从这两张表中获得团队的总付款。

我是特定球队和所有球队中每位球员的薪水总和。

我想过尝试

select t_id,team_name,sum(b.payment) as total_payment from table_team a
left join table_player b on a.t_id = b.t_id

3 个答案:

答案 0 :(得分:1)

加入子查询,计算每个团队的总付款额:

SELECT t1.t_id, t1.team_name, t2.total_payment
FROM table_team t1
INNER JOIN
(
    SELECT t_id, SUM(payment) AS total_payment
    FROM table_player
    GROUP BY t_id
) t2
    ON t1.t_id = t2.t_id
-- WHERE t1.team_name IN ('ABC', 'XYZ')

答案 1 :(得分:1)

select t_id,team_name,sum(b.payment) as total_payment 
from table_team a
left join table_player b on a.t_id = b.t_id
group by t_id,team_name

答案 2 :(得分:1)

int[][] iAmArray1,iAmArray2;

iAmArray1=new int[3][];
iAmArray2=new int[4][];

只需添加select t_id,team_name,sum(isnull(b.payment,0)) as total_payment from table_team a left join table_player b on a.t_id = b.t_id group by t_id, team_name ,就可以了