0

以下 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。

谢谢

4

2 回答 2

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 
于 2013-02-07T02:21:17.430 回答
0

这是因为您也是按 post_metric_type_id 分组的。加入和分组到那个领域的目的是什么?如果您希望结果包含该字段,请将其添加到您的 select 语句中。

但是,要获得 post_id 的总和,请将其从 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 - 取决于您的需要。

祝你好运。

于 2013-02-07T02:10:55.077 回答