2013-02-07 44 views
0

以下SQL語句會生成下面列出的結果。問題是,我如何修改此聲明以提供每個post_id的總和?例如,post_id 1應該= 25,並且post_id 2應該= 758.SQL:SUM返回結果的MAX值的總和

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:value; 1:0; 1:25; 1:0; 2:110; 2:588; 2:60;

1 = 25; 2 = 758

感謝

+0

作爲一個說明,正確格式的代碼應該有四個空格縮進。 – tadman

回答

0

這是因爲你被post_metric_type_id分組及。加入和分組的目的是什麼?如果您希望結果包含該字段,請將其添加到您的選擇語句中。

但是,要獲得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 - 取決於您的需求。

祝你好運。

+0

謝謝你sgeddes! – Jim

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 
+0

+1 - 甚至沒有查看內部查詢,只是GROUP BY。好決定。 – sgeddes