1

我在尝试对两个不同表中的一个共同用户 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

...但我不知道如何在不创建第三个视图作为“垫脚石”的情况下将两个表中每个玩家的值相加。有任何想法吗?

4

2 回答 2

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 的结果,以及多年来在特定日期得分的总和。

于 2013-11-14T17:10:42.550 回答
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

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

于 2013-11-14T17:28:16.467 回答