我有两张桌子。
表1是:
Week / Team / Player / Stat1 / Stat2 / Stat3 / ...<br>
1 / Team1 / Player1 / # / # / # / ...<br>
1 / Team2 / Player2 / # / # / # / ...
表2是:
Player / Team / Played Game / Tiebreaker /
Player1 / Team1 / N / #
Player2 / Team2 / Y / #
Play Play游戏显示Y表示他们至少玩过一场比赛而N表示他们没有玩任何游戏。
我想要做的是按表1中每个玩家的列数统计并将表2中的决胜局值添加到它,但我想要一个条件,如果Played Game等于N,那么只返回0作为值。希望这是有道理的。
这是我的代码:
$sql = "SELECT Player,
SUM (Stat1) AS Stat1,
SUM (Stat2) AS Stat2,
SUM (Stat3) AS Stat3
FROM Table 1
GROUP BY Player
ORDER BY Stat1 DESC";
这显然只是为我总结了价值。我的问题是我不确定如何从其他表中检索信息并在同一查询中执行我想要的操作。我已经尝试了一个CASE WHEN和IF语句,但是还没有奏效。我是新人,所以我想学习,但我现在被卡住了。
非常感谢任何帮助。
答案 0 :(得分:0)
你想要条件求和,它使用CASE
语句作为聚合函数的参数:
SELECT t1.Player,
(SUM(CASE WHEN t2.Played = 'Y' THEN Stat1 ELSE 0 END) +
MAX(CASE WHEN t2.Played = 'Y' THEN TIEBREAKER ELSE 0 END)
) AS Stat1,
SUM(CASE WHEN t2.Played = 'Y' THEN Stat2 ELSE 0 END) AS Stat2,
SUM(CASE WHEN t2.Played = 'Y' THEN Stat3 ELSE 0 END) AS Stat3
FROM Table1 t1 LEFT JOIN
Table2 t2
ON t1.player = t2.player AND t1.team = t2.team
GROUP BY t1.Player
ORDER BY Stat1 DESC;
答案 1 :(得分:0)
从两个表中获取数据包括
中的另一个表`FROM table1, table2`
并加入
`Where Table1.Player=Table2.Player`
这样,在结果中,Player列将为每个玩家提供一次,总和列(如Stat1,Stat2,Stat3)将为Table2中具有Table1中相应Player的每个记录的Stat列求和(这是所有这些)。
我不知道php部分,我不知道你的意思
我只想在统计数据汇总后添加一次决胜局。
但我认为此查询将适用于其余部分。
`SELECT Table2.Player, #I assume Table1.Player has repeat values and stuff,
SUM ( if ( Table2.PlayedGame="Y", Table1.Stat1, 0) ) AS Stat1,
SUM ( if ( Table2.PlayedGame="Y", Table1.Stat2, 0) ) AS Stat2,
SUM ( if ( Table2.PlayedGame="Y", Table1.Stat3, 0) ) AS Stat3
FROM Table1, Table2
Where Table1.Player = Table2.Player
GROUP BY Player
ORDER BY Stat1 DESC";`