2

我正在研究一个公式,我根据其他单元格的值在一行和一列中添加多个值。例如,我有以下工作代码:

$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 新手,所以我不确定设置它的正确/最佳方式。谢谢

4

1 回答 1

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过滤器SELECTIF

其他可能性使用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;
于 2013-04-15T20:58:31.537 回答