跨多个表的求和值

时间:2013-11-14 16:54:08

标签: mysql sum

我在尝试从两个不同的表中将一个字段GROUPED BY与一个普通用户ID相加时遇到了麻烦。

为了给你更多信息......我试图按日期跟踪球员表现(即:11月14日所有得分)。数据库是分开的,一个桌子用于常规赛,一个桌子用于季后赛。所以,例如,一名球员可能在2001年5月3日参加常规赛季比赛......但是在2005年5月3日进行了一场季后赛。

所以,我正在尝试用所有日期的每个玩家的总和建立一个视图。

我对一张桌子的所作所为:

SELECT PlayerId,sum(Points) as TOT_PTS 
FROM RS_games 
WHERE DAY(Date)=$cur_day 
  AND MONTH(Date)=$cur_month 
GROUP BY PlayerId

...但是我无法想象如何在不创建第三个视图作为“踏脚石”的情况下,如何将每个玩家的值相加到两个表中。 有什么想法吗?

2 个答案:

答案 0 :(得分:1)

如果你想要结果(DAY-MONTH),你可以这样做:

SELECT playerID, 
       CONCAT (DAY(DATE), '-', MONTH(DATE)) AS DAY_MONTH, 
       SUM(points) AS Total_Points
FROM (
  SELECT playerID, DATE, points
  FROM rs_games  
  UNION ALL  
  SELECT playerID, DATE, points
  FROM po_games
  ) a
GROUP BY 1, 2

sqlfiddle demo

这样,你最终会得到每个playerId,dd-mm以及多年来在特定日期得分的总和的结果。

答案 1 :(得分:0)

只是说出我的意思:

select
  ALL_players.PlayerID as PlayerID
  COALESCE(reg.Points, 0) + COALESCE(po.Points, 0) as Points
from
ALL_players
left join
(select PlayerID, DATE(Date) as Date, sum(Points) as Points 
 from RS_games
 WHERE DAY(Date)=$cur_day AND MONTH(Date)=$cur_month
 group by PlayerID) as reg
on reg.PlayerID = ALL_players.PlayerID
left join
(select PlayerID, DATE(Date) as Date, sum(Points) as Points 
 from PO_games group by DATE(Date), PlayerID
 WHERE DAY(Date)=$cur_day AND MONTH(Date)=$cur_month
 group by PlayerID) as po
on po.PlayerID = ALL_players.PlayerID

编辑:再次查看要求,这需要一个完整的外部联接或一些调整...调整(应该现在正在工作)