[英]mySQL - Sum columns in a table based on one field
I have a table in my database that's structured as such: 我的数据库结构如下:
Week Team Player Plants Score Ball Kills
1 Team1 Player1.1 1 1 1
1 Team1 Player1.2 2 1 0
1 Team2 Player2.1 0 4 3
1 Team2 Player2.2 3 1 5
2 Team1 Player1.1 2 7 11
2 Team1 Player1.2 2 2 0
2 Team2 Player2.1 0 0 1
2 Team2 Player2.2 2 1 1
I'm trying to output a table where I sum all the fields of the table based on a Player (Eg sum all the values for Player1.1 to get the total for each column) 我正在尝试输出一个表,在该表中,我根据一个Player汇总该表的所有字段(例如,对Player1.1的所有值求和以获取每一列的总计)
So for instance: 因此,例如:
/ Team / / Player / / Plants / / Score / / Ball Kills /..... /团队/ /球员/ /植物/ /得分/ /球击杀/ .....
/ Team1 / / Player1.1 / / 3 / / 8 / / 12 /..... / Team1 / / Player1.1 / / 3 / / 8 / / 12 / .....
/ Team1 / / Player1.2 / / 4 / / 3 / / 0 /..... /队1 / /玩家1.2 / / 4/3 / / 0 / .....
/ Team2 / / Player2.1 / / 0 / / 4 / / 4 /..... / Team2 / / Player2.1 / / 0 / / 4 / / 4 / .....
/ Team2 / / Player2.2 / / 5 / / 2 / / 6 /..... / Team2 / / Player2.2 / / 5 / / 2 / / 6 / .....
This is the code I have so far. 这是我到目前为止的代码。 Obviously it just outputs the entire table. 显然,它只是输出整个表。
$sql = "SELECT * FROM Table1";
$Data = mysql_query ($sql,$con);
echo '<table class="db-table" cellpadding="0" cellspacing="0">
<tr>
<th>Team</th>
<th>Player</th>
<th>Plants</th>
<th>Ball Kills</th>
<th>First Touch</th>
<th>Fast Break</th>
<th>Runner Score</th>
<th>Tank Score</th>
<th>Defender Score</th>
</tr>';
while ($results = mysql_fetch_array ($Data)){
echo "<tr>";
echo "<td>" . $results['Team'] . "</td>";
echo "<td>" . $results['Player'] . "</td>";
echo "<td>" . $results['Plants'] . "</td>";
echo "<td>" . $results['Ball Kills'] . "</td>";
echo "<td>" . $results['First Touch'] . "</td>";
echo "<td>" . $results['Fast Break'] . "</td>";
echo "<td>" . $results ['Runner Score'] . "</td>";
echo "<td>" . $results['Tank Score'] . "</td>";
echo "<td>" . $results['Defender Score'] . "</td>";
echo "</tr>";
}
echo "</table>";
I've looked at many examples of my problem, however it doesn't do what I want when I put the code in, and I can't figure out why. 我看过很多关于我的问题的示例,但是当我放入代码时,它并没有实现我想要的功能,我也弄不清原因。 I am new to php, so any help would be appreciated. 我是php新手,因此将不胜感激。
You can use one query using group by
您可以使用group by
使用一个查询
select
t.Team,
t.Player,
sum(t.Plants) as Plants,
sum(t.Score) as Score,
sum(t.`Ball Kills`) as `Ball Kills`
from table1 t1
group by
t.Team,
t.Player
try this: 尝试这个:
SELECT
t.Team,t.Player,sum(t.'Ball Kills') as 'Ball Kills',sum(t.Plants) as plants,
sum(t.Score) as Score
FROM Table1 t
GROUP BY Team,player
ORDER BY 'Ball Kills',plants
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.