dqroc48068 2018-07-10 17:45
浏览 55
已采纳

基于特定标准对数组中的列求和

I am trying to make a page in PHP more efficient. The goal is to tally payments for jobs that were delivered between two dates. The payments are in a separate table but only have a payment date, not a delivery date. Previously, I had a while loop to select all records between two dates which then carried out another query on the payments table within the loop. This was painfully slow so i have done this in 2 queries and put the results into an array as shown below.

{ [20253]=> array(5) { ["contNo"]=> string(5) "20253" ["contDate"]=> string(19) "2017-01-25 15:15:34" ["hireStart"]=> string(10) "2017-01-27" ["hireEnd"]=> string(10) "2017-01-30" ["revenue"]=> array(2) { [0]=> array(2) { ["contNo"]=> string(5) "20253" ["revenue"]=> string(6) "197.85" } [1]=> array(2) { ["contNo"]=> string(5) "20253" ["revenue"]=> string(5) "70.22" } } }

What i would now like to do is sum the revenue when the hireStart date is between x and y dates and also sum the revenue when the contDate is between x and y date.

Does anyone have an idea how I can do this? Just to point out that is just one record in the array of 14000 results so efficiency is what i need most! The code used to generate the array is below.

while ($contNums = $result2->fetch_assoc()) {
    //for each contract in date range sum revenue
    $contNoArray[$contNums['contNo']]=$contNums;
}
mysqli_free_result($result2);

$stmt2="SELECT contNo, revenue FROM `payments`";
$result3 = $conn->query($stmt2);
while ($payments = $result3->fetch_assoc()) {
    $contNoArray[$payments['contNo']]['revenue'][]=$payments;
}
foreach($contNoArray AS $contract)
{
    This is where i am stuck!
}
  • 写回答

1条回答 默认 最新

  • doudong1117 2018-07-11 09:39
    关注

    Thanks to Jonathan that suggested the left join. Should have thought of this before! I would still like to know how (code wise) to do it as i was initially attempting if anyone does know. The solution to do it in the query is below...

    SELECT sum(P.revenue) as revTotal
    FROM contracts C LEFT JOIN payments P
    ON P.contNo = C.contNo
    where C.contDate BETWEEN '2017-01-01' AND '2018-12-31'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大