簡體   English   中英

MySQL-基於一個字段的表中的列總和

[英]mySQL - Sum columns in a table based on one field

我的數據庫結構如下:

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   

我正在嘗試輸出一個表,在該表中,我根據一個Player匯總該表的所有字段(例如,對Player1.1的所有值求和以獲取每一列的總計)

因此,例如:

/團隊/ /球員/ /植物/ /得分/ /球擊殺/ .....
/ Team1 / / Player1.1 / / 3 / / 8 / / 12 / .....
/隊1 / /玩家1.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新手,因此將不勝感激。

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

嘗試這個:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM