mySQL中的条件求和?

时间:2011-07-26 07:33:31

标签: php mysql codeigniter

我不是很擅长SQL,所以我一直试图通过PHP处理这个并进行非常基本的mySQL查询,但显然我的内存不足(在PHP中)因为我处理了很多数据(以及大量可怕的嵌套foreach)。我希望可能有一种方法可以重新编写我的SQL,以免发生这种情况。

这是我正在处理的表格(仅显示相关字段):

组织

  • ORGID

FundingCycles

  • CycleID
  • NonUnityCut​​BackAmount
  • UnityCut​​BackAmount

AdministrativeRequests

  • CycleID
  • ORGID
  • AmountRequested
  • AmountFunded
  • PerOff

CapitalRequests

  • CycleID
  • ORGID
  • AmountRequested
  • AmountFunded
  • PerOff

EventRequests

  • CycleID
  • ORGID
  • AmountRequested
  • AmountFunded
  • PerOff
  • UnityReq

所以,这是复杂的部分。我需要为AmountRequestedAmountFunded的每个组织创建总和(这两个似乎很容易,但不确定跨多个表的求和),以及来自请求的计算字段AmountAfterCutback在所有请求表中(AdministrativeRequestsCapitalRequestsEventRequests)。

AmountAfterCutback等于:AmountFunded - (AmountFunded * Cutback)。

如果削减只是一个值,这可能很简单。但是,Cutback来自FundingCycles表。所以我不能直接求和并应用削减,我必须找出每个请求的削减,并且为此我必须查看每个请求,然后通过其CycleID检查,看看是什么该请求的削减在FundingCycles表中。

默认情况下,Cutback等于NonUnityCutBack。但是,如果请求是Unity请求(仅EventRequestsUnityReq == 1),则削减等于UnityCutBack。然而,它变得更具挑战性,因为削减可以单独应用于每个请求,覆盖统一或不一致的削减(如果PerOff is > 0)。

所以,不知何故,我必须总结一个组织所做的每一个请求,并正确计算上面提到的字段。我将在下面展示我的解决方案,我将警告它肯定不是很漂亮,并且在这一点上甚至没有功能,因为它在尝试通过PHP处理它时耗尽了内存。我知道有更好的方法来做到这一点。有些方法可以对每个请求进行条件计算,这样可以在查询中求和,而不是我下面笨重的PHP解决方案?有任何想法吗?感谢任何有耐心甚至读到这一点的人,我知道这是一个问题的PITA。非常感谢任何帮助!

function calculate_public_records()
{
      $total_req_total = 0;
      $total_funded_total = 0;
      $total_cutback_total = 0;

      $organizations = array();

      foreach($this->organizations as $org)
      {
          $id = $org['OrgID'];
          $org_req_total = 0;
          $org_funded_total = 0;
          $org_cutback_total = 0;

          $cycles = array();

          foreach($this->cycles as $cycle)
          {
                $cycle_req_total = 0;
                $cycle_funded_total = 0;
                $cycle_cutback_total = 0;

                $cycle_requests = array();

                foreach($this->request_types as $type)
                {
                    $reqs = $this->funding_request_model->getRequests($type, $cycle['CycleID'], $id);
                    foreach($reqs as $r)
                    {
                        $cutback = $cycle['NonUnityCutBack'];
                        if ($type == "Event") $cutback = ($r->UnityReq == 1) ? $cycle['UnityCutBack'] : $cutback;
                        $cutback = ($r->PerOff != 0) ? $r->PerOff : $cutback;

                        $request = array();
                        $request['id']        = $r->ReqID;
                        $request['type']      = $type;
                        $request['name']      = $r->Title;
                        $request['requested'] = number_format($r->RequestTotal, 2);
                        $request['funded']    = number_format($r->AmtFunded, 2);
                        $request['cutback']   = number_format(($r->AmtFunded - ($r->AmtFunded * $cutback)), 2);

                        $cycle_req_total += $request['requested'];
                        $cycle_funded_total += $request['funded'];
                        $cycle_cutback_total += $request['cutback'];

                        $cycle_requests[] = $request;
                    }

                }

                $cycle_totals = array();
                $cycle_totals['requested'] = number_format($cycle_req_total, 2);
                $cycle_totals['funded'] = number_format($cycle_funded_total, 2);
                $cycle_totals['cutback'] = number_format($cycle_cutback_total, 2);

                $org_req_total += $cycle_req_total;
                $org_funded_total += $cycle_funded_total;
                $org_cutback_total += $cycle_cutback_total;

                $cycles[] = array('name' => $cycle['CycleName'], 'requests' => $cycle_requests, 'totals' => $cycle_totals);
          }

          $org_totals = array();
          $org_totals['requested'] = number_format($org_req_total, 2);
          $org_totals['funded'] = number_format($org_funded_total, 2);
          $org_totals['cutback'] = number_format($org_cutback_total, 2);

          $total_req_total += $org_req_total;
          $total_funded_total += $org_funded_total;
          $total_cutback_total += $org_cutback_total;

          $organizations[] = array('id' => $org['OrgID'], 'name' => $org['Organization'], 'cycles' => $cycles, 'totals' => $org_totals);
      }

      $totals = array();
      $totals['requested'] = number_format($total_req_total, 2);
      $totals['funded'] = number_format($total_funded_total, 2);
      $totals['cutback'] = number_format($total_cutback_total, 2);

      return array('organizations' => $organizations, 'totals' => $totals);

计算摘要:

# For tables AdministrativeRequests, CapitalRequests & EventRequests, calculate:

    SUM(AmountRequested)
    SUM(AmountFunded)

# For tables AdministrativeRequests, CapitalRequests & EventRequests, calculate:

    AmountAfterCutback = AmountFunded - (AmountFunded * Cutback)

# Cutback calculation pseudocode

if( <table>.PerOff > 0 ) {
    Cutback = <table>.PerOff
} elseif ( <table> == EventRequests && EventRequests.UnityReq == 1 ) {
    Cutback = FundingCycles.UnityCutBack
} else {
    Cutback = FundingCycles.NonUnityCutBack
}

2 个答案:

答案 0 :(得分:2)

学习SQL。快速阅读表明答案可能是......

    SELECT orgid
    , SUM(requested) AS amountrequested
    , SUM(funded) AS amountfunded
    , SUM(IF(unityreq=1, unitycutback, nonunitycutback) * funded) 
           AS amountaftercutback
    FROM
    ( 
      SELECT cycleid, orgid, unityreq, 
        SUM(amountrequested) as requested, SUM(amountfunded) as funded
      FROM
        (
           (
           SELECT cycleid, orgid, AmountRequested, AmountFunded, 0 as unityreq
           FROM administrativerequests 
           )
           UNION
           (
           SELECT cycleid, orgid, AmountRequested, AmountFunded, 0 as unityreq
           FROM capitalrequests
           )
           UNION
           (
           SELECT cycleid, orgid, AmountRequested, AmountFunded, unityreq
           FROM eventrequests
           )
        ) ilv
      GROUP BY cycleid, orgid, unityreq
    ) ilv,
    fundingcycles fc
    WHERE fc.cycleid=ilv.cycleid
    GROUP BY orgid

答案 1 :(得分:2)

以下是我的尝试 - 已更新为使用UNION ALL代替UNION

SELECT OrgID,
       SUM(AmountRequested),
       SUM(AmountFunded),
       SUM(AmountFunded - (
           AmountFunded * 
           IF( PerOff > 0,
               PerOff,
               IF( UnityReq = 1,
                   UnityCutBackAmount,
                   NonUnityCutBackAmount
               )
           )
       )) AS AmountAfterCutback
  FROM (
SELECT o.OrgID,
       ar.AmountRequested,
       ar.AmountFunded,
       ar.PerOff,
       null AS UnityReq,
       fc_ar.CycleID,
       fc_ar.NonUnityCutBackAmount,
       fc_ar.UnityCutBackAmount
  FROM Organizations o
  JOIN AdministrativeRequests ar
    ON ar.OrgID = o.OrgID
  JOIN FundingCycles fc_ar
    ON fc_ar.CycleID = ar.CycleID
 UNION ALL
SELECT o.OrgID,
       cr.AmountRequested,
       cr.AmountFunded,
       cr.PerOff,
       null AS UnityReq,
       fc_cr.CycleID,
       fc_cr.NonUnityCutBackAmount,
       fc_cr.UnityCutBackAmount
  FROM Organizations o
  JOIN CapitalRequests cr
    ON cr.OrgID = o.OrgID
  JOIN FundingCycles fc_cr
    ON fc_cr.CycleID = cr.CycleID
 UNION ALL
SELECT o.OrgID,
       er.AmountRequested,
       er.AmountFunded,
       er.PerOff,
       er.UnityReq,
       fc_er.CycleID,
       fc_er.NonUnityCutBackAmount,
       fc_er.UnityCutBackAmount
  FROM Organizations o
  JOIN EventRequests er
    ON er.OrgID = o.OrgID
  JOIN FundingCycles fc_er
    ON fc_er.CycleID = er.CycleID
) tmp
 GROUP BY OrgID;