来自不同表的SQL SUM和COUNT

时间:2018-10-18 18:38:10

标签: sql

表格:

 UserReward:
        UserRewardID PK
        RewardID FK
        UserID FK

    UserBadge:
        UserBadgeID PK
        BadgeID FK
        UserID FK

    UserScore:
        UserScoreID PK
        UserID FK
        LeaderboardID FK

我需要知道分数的总和,用户徽章的数量和userReward的数量。 我试过了,但是值不对:

Select 
  u.username,
  sum(us.score) as Soma_Score, 
  count(ur.userId) as Numero_de_rewards, 
  count(ub.userId) as Numero_de_crachas
from [user] u 
join userscore us on u.userId = us.userID
join userbadge ub on ub.userid = u.userid
join userreward ur on ur.userid= u.userid
group by u.username

2 个答案:

答案 0 :(得分:3)

在汇总行之前,您是否查看过行?您的JOIN重复了很多行。

最好的方法是在聚合后联接行:

with score(userid, score) as (
Select userid
     , sum(us.score) as Soma_Score
  from userscore us
  group by userid
), rewards (userid, rewards) as (
select userid
     , count(ur.userId) as Numero_de_rewards
  from  userreward ur
  group by userid
), crachas (userid, crachas) as
select userid
    , count(userId)
  from userbadge
  group by userid
)
select
     u.userid
   , score.score
   , rewards.rewards
   , crachas.crachas
from user u
left join score on u.userid=score.userid
left join rewards on u.userid=rewards.userid
left join crachas on u.userid=crachas.userid

答案 1 :(得分:2)

尝试:

SELECT
    u.username,
    (SELECT SUM(us.score) FROM userscore us WHERE us.userid = u.userid) as Soma_Score,
    (SELECT COUNT(ur.userId) FROM userreward ur WHERE ur.userid = u.userid) as numero_de_rewards, 
    (SELECT COUNT(ub.userId) FROM userbadge ub WHERE ub.userid = u.userid) as numero_de_crachas
FROM [user] u