mysql的求和结果和分组方式,并再次求和

aiqt4smr  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(488)

我有一个问题,我需要求和后,我提出的金额trid列总和

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`

结果

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

现在我想把trid的和加起来,所以求和trid=682,在两个活动中的结果应该是50.9
预期结果

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
nbewdwxp

nbewdwxp1#

考虑到查询的输出存储在 temptable . 请尝试下面的查询。希望有帮助。

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;

如果可以提供有关查询中包含的表和示例数据的更多详细信息,我们可以尝试直接从它们获取数据。

相关问题