带有SUM结果的MYSQL以及再次GROUP BY和SUM

时间:2018-09-19 17:37:38

标签: mysql

我有一个查询,求和后需要对trid列求和

__in

结果

query = """select myfield from mytable join (values 
             ('v1'), ('v2'), ..., ('vN')
           ) as lookup(value) on lookup.value = mytable.myfield"""
r = RawSQL(query, [])
mymodel.filter(myfield__in=r)

现在,我希望组合trid的总和,因此sumd = 682的结果在两个campaign_id中应该为50.9

预期结果

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`

1 个答案:

答案 0 :(得分:0)

考虑到查询的输出存储在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;

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