Question

I am working on a formula where I am adding multiple values in a row and column depending on the values of other cells. For example I have the following working code:

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

However I want to add more columns that are also sums of other rows/columns and don't know how to do this while still keeping everything Grouped by the column 'School'. What I essentially want is the following, but the code is incorrect:

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

I'm new to PHP so I'm not sure the correct/optimal way to go about setting this up. Thanks

Was it helpful?

Solution

this is the query you should use to get the 2 totals:

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;

See how it adds according to the event columns? The trick is to pass a WHERE filter within the SELECT clause through conditional execution (IF)

Other possibility using 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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top