2016-02-03 106 views
0

我有一個包含facebook廣告數據的MYSQL表。在mysql中添加相同行的值

我正在使用Facebook Ads API獲取特定帳戶的所有廣告。 在結果中,我有一些具有相同名稱的廣告組,因爲在不同的時間段內adset被刪除。

F.x.

NAME      SPEND  
Gistrup MSN Standard - 11 
Storvorde MSN Standard - 12 
Vejgaard MSN Standard - 13 
Aalborg MSN Standard - 14 
Gistrup MSN Standard - 15 
Storvorde MSN Standard - 16 
Vejgaard MSN Standard - 17 
Aalborg MSN Standard - 18 

的數量在adset所花。

然後,我有這樣的腳本來選擇數據,並輸出作爲JSON

$fb_sql = "SELECT * FROM $table WHERE id_campaign_shortname = '". $_GET["lpage"] ."' AND date_from = '". $date_from ."' AND date_to = '". $date_to ."'"; 

     $fb_sth = $db->dbh->query($fb_sql); 
     $fb_result = $fb_sth->fetchAll(); 

     $merged_data = array_merge($fb_result); 

     $jsonArray = array(); 

     if(count($merged_data) > 0) { 

      $total = 0; 

      foreach($merged_data as $elm) { 

       array_push($jsonArray, array(
        "campaign" => array(
         "campaignName" => $elm["campaign_name"], 
         "campaignAdsetName" => $elm["adset_name"], 
         "campaignReach" => $elm["reach"], 
         "campaignSpend" => $elm["amount_spent"], 
         "campaignCPC" => $elm["cpc"], 
         "campaignClicks" => $elm["clicks"], 
         "campaignId" => $elm["id_name"], 
         ) 
        ) 
       ); 

       $total += $elm["reach"]; 

      } 


      $jsonCampaignDataArray = array("campaignData" => $jsonArray); 
      $jsonTotalReach = array("totalReach" => $total); 

      $finalArray = array_merge($jsonCampaignDataArray, $jsonTotalReach); 

      $json = json_encode($finalArray); 

      echo $_GET['jsonp']. '('. $json . ')'; 

我怎麼能採取的所有行具有相同的名稱和將它們組合起來,以使支出值將加在一起爲同行,即兩個「Gistrup MSN標準」將被合併,SPEND值將爲26(11 + 15)。然後

我的JSON輸出將包含類似:

NAME      SPEND  
Gistrup MSN Standard - 26 
Storvorde MSN Standard - 28 
Vejgaard MSN Standard - 30 
Aalborg MSN Standard - 32 

回答

1

您可以通過使用group by條款改變你的SQL。
事情是這樣的 -

SELECT `NAME`, SUM(`SPEND`) FROM <TABLE_NAME> GROUP BY NAME 

在你的情況下,查詢會是這個樣子 -

// You will need to add the col names here 
$fb_sql = "SELECT `NAME`, SUM(`SPEND`) FROM $table WHERE id_campaign_shortname = '". $_GET["lpage"] ."' AND date_from = '". $date_from ."' AND date_to = '". $date_to ."' GROUP BY NAME"; 
+0

當然!就那麼簡單!謝謝! –

1

選擇選擇id_campaign_shortname,SUM(支出)按id_campaign_shortname