我正在研究一个公式,我在行和列中添加多个值,具体取决于其他单元格的值。例如,我有以下工作代码:
$result = mysql_query("SELECT School,SUM(Wins + Losses) as total FROM tennis GROUP BY School");
echo "<table border='1'>
<tr>
<th>School</th>
<th>Score</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['School'] . "</td>";
echo "<td>" . $row['total'] . "</td>";
echo "</tr>";
}
但是我想添加更多的列,这些列也是其他行/列的总和,并且不知道如何执行此操作,同时仍然保留按“学校”列分组的所有内容。我基本上想要的是以下内容,但代码不正确:
$result = mysql_query("SELECT School,SUM(Wins + Losses) as 1sttotal FROM tennis WHERE Event='1st Singles', SUM(Wins + Losses) as 2ndtotal FROM tennis WHERE Event='2nd Singles' GROUP BY School");
echo "<table border='1'>
<tr>
<th>School</th>
<th>1st Singles</th>
<th>2nd Singles</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['School'] . "</td>";
echo "<td>" . $row['1sttotal'] . "</td>";
echo "<td>" . $row['2ndtotal'] . "</td>";
echo "</tr>";
}
我是PHP的新手,所以我不确定正确/最佳的设置方法。感谢
答案 0 :(得分:1)
这是您应该使用的查询来获得2个总计:
SELECT
School,
SUM(IF(Event='1st Singles', Wins + Losses, 0)) as 1sttotal,
SUM(IF(Event='2nd Singles', Wins + Losses, 0)) as 2ndtotal
FROM tennis
GROUP BY School;
根据event
列了解它的添加方式?诀窍是通过条件执行(WHERE
)在SELECT
子句中传递IF
过滤器
使用CASE WHEN
的其他可能性:
SELECT
School,
SUM(
CASE
WHEN Event='1st Singles' THEN Wins + Losses
ELSE 0
END
) as 1sttotal,
SUM(
CASE
WHEN Event='2nd Singles' THEN Wins + Losses
ELSE 0
END
) as 2ndtotal
FROM tennis
GROUP BY School;