SQL:SUM返回结果的MAX值的SUM

时间:2013-02-07 02:07:11

标签: mysql sql

以下SQL语句生成下面列出的结果。问题是,如何修改此语句以提供每个post_id的总和?例如,post_id 1应为= 25,post_id 2应为= 758。

SELECT t.post_id,
SUM(maxpostmetric) as sumvalue 
  FROM ( 
    SELECT post_metrics.post_id, 
    post_metrics.post_metric_type_id, 
    MAX( post_metrics.value ) maxpostmetric 
    FROM post_metrics 
    INNER JOIN posts ON posts.id = post_metrics.post_id 
    WHERE posts.channel_id = 2268
    GROUP BY post_metrics.post_id, post_metrics.post_metric_type_id 
    ORDER BY post_metrics.id 
  )t 
INNER JOIN post_metric_types ON post_metric_types.id = t.post_metric_type_id 
GROUP BY t.post_id, t.post_metric_type_id 

POST_ID:值; 1:0; 1:25; 1:0; 2:110; 2:588; 2:60;

1 = 25; 2 = 758。

由于

2 个答案:

答案 0 :(得分:2)

您无需聚合两次:

SELECT post_metrics.post_id, MAX( post_metrics.value ) maxpostmetric 
FROM post_metrics INNER JOIN
     posts
     ON posts.id = post_metrics.post_id 
WHERE posts.channel_id = 2268
GROUP BY post_metrics.post_id 
ORDER BY post_metrics.id 

答案 1 :(得分:0)

这是因为你也通过post_metric_type_id进行分组。加入的目的和对该领域的分组是什么?如果希望结果包含该字段,请将其添加到select语句中。

但是,要获取post_id的SUM,请从GROUP BY子句中删除它,你应该好好去。

SELECT t.post_id,
       SUM(maxpostmetric) as sumvalue 
  FROM ( 
    SELECT post_metrics.post_id, 
    post_metrics.post_metric_type_id, 
    MAX( post_metrics.value ) maxpostmetric 
    FROM post_metrics 
    INNER JOIN posts ON posts.id = post_metrics.post_id 
    WHERE posts.channel_id = 2268
    GROUP BY post_metrics.post_id, post_metrics.post_metric_type_id 
    ORDER BY post_metrics.id 
  )t 
INNER JOIN post_metric_types ON post_metric_types.id = t.post_metric_type_id 
GROUP BY t.post_id

您也可以删除您的INNER JOIN - 取决于您的需求。

祝你好运。