收集的总和查询

时间:2015-02-06 04:44:32

标签: sql-server-2008 tsql

我有两张桌子:

Fixture (id, homeId, awayId...)
FixtureStats(id,playerId, teamOwnerId, rating, goals)

我希望显示每位球员的目标总数以及球员所属的球队目标。

 PlayerId TeamOwnerId Goals  TeamGoals
    1              2      0        9
    2              2      1        9
    3              2      3        9
    4              2      5        9
    5              3      0        12       

....

下面的sql查询仍缺少teamgoals

SELECT TOP (100)
       PERCENT fs.teamownerid,
       fs.playerid,
       Count(f.id)  AS Apps,
       Sum(fs.goal) AS Goals
FROM   dbo.fixturestats AS fs
       INNER JOIN dbo.fixture AS f ON fs.fixtureid = f.id
WHERE  ( fs.rating > 0 )
GROUP  BY fs.playerid, fs.teamownerid  

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
    X.playerid,
    X.teamownerid,
    X.goals,
    (   SELECT Sum(goal)
        FROM   fixturestats
        WHERE  X.teamownerid = teamownerid
    ) AS TeamGoals
FROM  (
        SELECT 
            TOP (100) PERCENT fs.teamownerid AS TeamOwnerId,
            fs.playerid    AS PlayerId,
            Count(f.id)    AS Apps,
            Sum(fs.goal)   AS Goals
        FROM   dbo.fixturestats AS fs
        INNER JOIN dbo.fixture AS f ON fs.fixtureid = f.id
        WHERE  ( fs.rating > 0 )
        GROUP  BY fs.playerid,fs.teamownerid
     ) AS X  

答案 1 :(得分:1)

您可以使用Sum-Over

select 
    *,
    Sum(Goals) over (partition by TeamOwnerId)
from 
    FixtureStats
where 
    (Rating > 0)