Mohammad Al Sayed
Mohammad Al Sayed

Reputation: 1

MYSQL with SUM results and GROUP BY and SUM Again

I have a query that I need to SUM the trid column after summing the raised amount

SELECT
  `ppm_campaign_id`.`meta_value` AS `campaign_id`,
  `trasnlations`.`trid`          AS `trid`,
  `ppm_campaign_value`.`meta_value` AS `raised`
FROM (((`thf_posts` `posts`
     LEFT JOIN `thf_postmeta` `ppm_campaign_id`
       ON (((`ppm_campaign_id`.`meta_key` = 'campaign_id')
            AND (`ppm_campaign_id`.`post_id` = `posts`.`ID`))))
    LEFT JOIN `thf_postmeta` `ppm_campaign_value`
      ON (((`ppm_campaign_value`.`meta_key` = 'campaign_value')
           AND (`ppm_campaign_value`.`post_id` = `posts`.`ID`))))
   LEFT JOIN `thf_icl_translations` `trasnlations`
     ON ((`trasnlations`.`element_id` = `ppm_campaign_id`.`meta_value`)))
WHERE ((`ppm_campaign_id`.`meta_value` IS NOT NULL)
       AND (`trasnlations`.`trid` IS NOT NULL))
GROUP BY `ppm_campaign_id`.`meta_value`

Result

campaign_id trid    raised
1022        564     4137.5
1031        564     3937.5
1698        653     3010
1700        655     10
1702        657     750
1712        653     3030
1713        655     20
1727        657     20
2163        682     0.9
2164        682     50
2166        683     200
2168        684     50

Now I want the sum of trid combined so summing trid = 682 the result of raised should be 50.9 in both campaign_id

Expected Result

 campaign_id    trid    raised
    1022        564     8075
    1031        564     8075
    1698        653     3010
    1700        655     10
    1702        657     750
    1712        653     3030
    1713        655     20
    1727        657     20
    2163        682     50.9
    2164        682     50.9
    2166        683     200
    2168        684     50

Upvotes: 0

Views: 119

Answers (1)

Arihant
Arihant

Reputation: 745

Considering the output of your query is stored in temptable. Please try the below query. Hope it helps.

SELECT t1.campaign_id, t1.trid, t2.raised_sum 
FROM temptable t1 JOIN (
SELECT trid, SUM(raised) as raised_sum 
FROM temptable GROUP BY trid) t2 
ON t1.trid=t2.trid
GROUP BY t1.campaign_id, t1.trid, t2.raised_sum;

If more details on the tables included in your query and sample data can be given, we can try to get the data directly from them.

Upvotes: 1

Related Questions