Reputation: 255
I am trying to display a summary table which is currently using multiple MySQL queries and I was wondering if it's possible to combine them into one.
I have a table called 'payments' with the fields amount and currency, and i'm trying to display a summary totals table for each of the currencies. As an example:
<table>
<tr>
<td>USD</td>
<td>EUR</td>
<td>GBP</td>
</tr>
<tr>
<? $q1 = mysqli_query("SELECT sum(amount) as total_USD from payments WHERE currency='USD'");
while($row1 = mysqli_fetch_assoc($q1)){ ?>
<td><? echo number_format($row1['total_USD'],0); ?></td>
<? } ?>
<? $q2 = mysqli_query("SELECT sum(amount) as total_EUR from payments WHERE currency='EUR'");
while($row2 = mysqli_fetch_assoc($q2)){ ?>
<td><? echo number_format($row2['total_EUR'],0); ?></td>
<? } ?>
<? $q3 = mysqli_query("SELECT sum(amount) as total_GBP from payments WHERE currency='GBP'");
while($row3 = mysqli_fetch_assoc($q3)){ ?>
<td><? echo number_format($row3['total_GBP'],0); ?></td>
<? } ?>
</tr>
</table>
In reality, I am using 12 currencies so I have 12 separate queries but it feels inefficient so I was wondering if there is an easier way to achieve the same result?
Many thanks!
Upvotes: 1
Views: 105
Reputation: 154
Solution 1:
SELECT currency, SUM(amount) as total FROM payments GROUP BY currency
Solution 2 :
$currencies=array(USD,EUR,GBP,...);
foreach($currencies as $currency){
$q1= mysqli_query("SELECT sum(amount) as total from payments WHERE currency='".$currency."'");
while($row1 = mysqli_fetch_assoc($q1)){
echo number_format($row1['total'],0);
}
}
Upvotes: 2
Reputation: 34284
You can use a GROUP BY here.
SELECT currency, SUM(amount) as total FROM payments GROUP BY currency
http://dev.mysql.com/doc/refman/5.1/en/group-by-modifiers.html
Upvotes: 1
Reputation: 212522
SELECT currency,
SUM(amount) as total
FROM payments
GROUP BY currency
Upvotes: 3