mySQL - 基于一个字段的表中的Sum列

时间:2014-05-04 14:43:45

标签: php mysql

我的数据库中有一个表格,其结构如下:

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   

我正在尝试输出一个表,其中我根据播放器对表的所有字段求和(例如,将Player1.1的所有值相加以获得每列的总数)

例如:

/ Team / / Player / / Plants / / Score / / Ball Kills / .....
/ Team1 / / Player1.1 / / 3 / / 8 / / 12 / .....
/ Team1 / / Player1.2 / / 4 / / 3 / / 0 / ..... / Team2 / / Player2.1 / / 0 / / 4 / / 4 / .....
/ Team2 / / Player2.2 / / 5 / / 2 / / 6 / .....

这是我到目前为止的代码。显然它只输出整个表格。

$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>";

我已经看过很多关于我的问题的例子,但是当我把代码放进去的时候它没有做我想要的,我无法弄清楚为什么。我是php的新手,所以任何帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:0)

您可以使用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

答案 1 :(得分:0)

试试这个:

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