我的表中有多个列..
col1 col2 col3 price
500 700 100 10
501 700 100 20
502 700 100 30
503 700 100 10
4 70
我需要计算col1并显示其总和。
并显示价格栏的总和......
但主要的是我需要在最后一行显示这个......在所有数据之后...如何选择这个并在最后一行回显......
请帮助我...
我需要完全回应,因为我将数据放在上表中......
我需要sql查询,还需要帮助才能仅回显最后一行中这两列的总和......
SELECT *,IFNULL(col1,'SUM'), count(*) as count FROM coupon_entry WHERE Group By col1 WITH ROLLUP
<?php if (is_array($data)) { foreach($data as $row){ ?>
<tr>
<td><?php echo htmlspecialchars($row['col1']); ?></td>
<td><?php echo htmlspecialchars($row['col2']); ?></td>
<td><?php echo htmlspecialchars($row['col3']); ?></td>
<td><?php echo htmlspecialchars($row['price']); ?></td>
</tr>
<?php } }?>
答案 0 :(得分:1)
一种解决方案是使用变量计算PHP中的总和:
<?php if (is_array($data)) {
$totalCol1 = 0;
$totalPrice = 0;
foreach($data as $row){
$totalCol1 += $row['col1'];
$totalPrice += $row['price'];
?>
<tr>
<td><?php echo htmlspecialchars($row['col1']); ?></td>
<td><?php echo htmlspecialchars($row['col2']); ?></td>
<td><?php echo htmlspecialchars($row['col3']); ?></td>
<td><?php echo htmlspecialchars($row['price']); ?></td>
</tr>
<?php }
<tr>
<td><?php echo $totalCol1;?></td>
<td></td>
<td></td>
<td><?php echo $totalPrice;?></td>
</tr>
}?>
答案 1 :(得分:0)
要么你必须做两个单独的查询,否则你必须在PHP中进行计算 - 任何一个都相当简单,尽管PHP解决方案可能会稍微(可忽略不计?)更快。
双查询:
$r = query('SELECT *
FROM yada-yada');
while ($row = fetch($r)) {
echo "<td>$row[col1]</td>\n";
echo "<td>$row[col2]</td>\n";
echo "<td>$row[col3]</td>\n";
echo "<td>$row[price]</td>\n";
}
$r2 = query('SELECT COUNT(*) as cnt, sum(col1) as sum_col1,
sum(price) as sum_price
FROM yada-yada...');
if ($row = fetch($r2)) {
echo "<td>$row['cnt']</td><td>$row['sum_col1']</td>...$row['sum_price']...\n";
}
用PHP计算:
$cnt = $sum_col1 = $sum_price = 0;
$r = query('SELECT *
FROM yada-yada');
while ($row = fetch($r)) {
echo "<td>$row[col1]</td>\n";
echo "<td>$row[col2]</td>\n";
echo "<td>$row[col3]</td>\n";
echo "<td>$row[price]</td>\n";
$cnt++;
$sum_col1 += $row['col1'];
$sum_price += $row['price'];
}
echo "<td>$cnt</td><td>$sum_col1</td>...$sum_price...\n";
答案 2 :(得分:0)
下面是我的sql查询来获取计数和列的总和。
SELECT COUNT(优惠券)总计,SUM(价格)AS TotalPrice FROM coupon_entry
把它放在桌子下方的单独行中......
<?php
foreach($tot as $tota)
?>
<tr style="background-color:#33CCFF;">
<td colspan="2" style="text-align:right; font-weight:bold;">Total Coupon</td>
<td><?php echo $tota['Total'];?></td>
<td style="text-align:right; font-weight:bold;">Total Amount in Rs</td>
<td><?php echo $tota['TotalPrice'];?></td>
</tr>
<?php }?>