我有一個PHP腳本,它啓動一個mysql查詢並返回一個結果集合的列。PHP生成不正確的算術結果
我需要對這些列進行進一步的聚合,並且正如我在腳本中所做的那樣。
問題是,對於20個限制中的前7個結果,計算公然不正確。
這是否與桌子很大的事實有關? (3.5m行)
我可以在SQL級別完成額外的聚合嗎?說A
是一個聚合和B
是一個聚合,我可以做C = B/A
?
//QUERY
$resultsquery = $db->prepare("SELECT 4_nationality.nationality, COUNT(DISTINCT(txn_id)) as numtrans,
SUM(sales) as sales, SUM(units) as units, YrQtr
FROM 1_txns INNER JOIN 4_nationality USING (nationality_id)
WHERE YrQtr LIKE :period
GROUP BY nationality_id
ORDER BY numtrans DESC
LIMIT 20");
$resultsquery->bindParam(":period", $period);
$resultsquery->execute();
//BUILD TABLE
echo "<div class='col-xs-12 col-sm-10'>";
echo $select;
echo "<table class='table table-striped'><tr>";
echo "<th>Nationality</th>";
echo "<th># Trans</th>";
echo "<th>Sales</th>";
echo "<th>Units</th>";
echo "<th>ATV</th>";
echo "<th>UPB</th>";
echo "<th>ARP</th>";
echo "</tr>";
while($row2 = $resultsquery->fetch(PDO::FETCH_ASSOC)){
//FURTHER CALCULATIONS
$nat = $row2['nationality'];
$numtrans = number_format($row2['numtrans'], 0);
$sales = number_format($row2['sales'], 0);
$units = number_format($row2['units'], 0);
$atvc = $sales/$numtrans;
$atv = number_format($atvc, 2);
$upbc = $units/$numtrans;
$upb = number_format($upbc, 1);
$arpc = $sales/$units;
$arp = number_format($arpc, 2);
//DISPLAY
echo "<tr>";
echo "<td>".$nat."</td>";
echo "<td>".$numtrans."</td>";
echo "<td>".$sales."</td>";
echo "<td>".$units."</td>";
echo "<td>".$atv."</td>";
echo "<td>".$upb."</td>";
echo "<td>".$arp."</td>";
echo "</tr>";
}
echo "</table>";
echo "</div>";
編輯:非常感謝這兩個問題的答案,這是很難選擇哪一個接受,因爲他們都幫助我以不同的方式。然而,我決定接受提供有關問題標題更多細節的答案。