2017-09-11 125 views
-1

我有這個模式的數據庫:了TRUNCATE 「無效使用組功能」(SUM())/ TIMESTAMPDIFF查詢

職位(ID:整數,created_at:日期時間,deleted_at:日期時間)
posts_reasons(POST_ID:整數reason_id:整數
原因(ID:整數,重量:整數)

我期待之間找到0的平均時間和posts.deleted_at(也稱爲時間缺失)爲每個組帖子的與reasons.weight與一系列10.一些樣品的結果可能是沿着這些路線的SUM:

Total Reason Weight (groups of 10) | Average Time To Deletion 
--------------------------------------+---------------------------- 
            0 | 987.36 
            10 | 872.01 
            20 | 819.34 
            30 | 742.77 

等。我排除了刪除時間大於一小時/ 3600秒以避免異常值的帖子。

這是查詢我到目前爲止:

SELECT 
    TRUNCATE(SUM(reasons.weight), -1) AS 'Reasons Weight', 
    AVG(TIMESTAMPDIFF(SECOND, posts.created_at, posts.deleted_at)) AS 'Avg Time To Deletion' 
FROM 
    posts 
    INNER JOIN posts_reasons ON posts_reasons.post_id = posts.id 
    INNER JOIN reasons ON reasons.id = posts_reasons.reason_id 
GROUP BY 
    posts.id, 
    TRUNCATE(SUM(reasons.weight), -1) 
HAVING 
    posts.deleted_at IS NOT NULL AND 
    TIMESTAMPDIFF(SECOND, posts.created_at, posts.deleted_at) <= 3600 
ORDER BY 
    TRUNCATE(SUM(reasons.weight), -1) ASC; 

我確信,我沒有聚合函數WHERE子句,給出如何常見的特定問題是;我也確保查詢分組在posts.id上,以使SUM(reasons.weight)聚合正常工作。

我仍然收到「組功能無效使用」錯誤。我需要做些什麼來解決這個問題?

回答

1

您不能在GROUP BY中使用聚合函數!

SELECT 
    TRUNCATE(reasons.weight, -1) AS 'Reasons Weight', 
    AVG(TIMESTAMPDIFF(SECOND, posts.created_at, posts.deleted_at)) AS 'Avg Time To Deletion' 
FROM 
    posts 
    INNER JOIN posts_reasons ON posts_reasons.post_id = posts.id 
    INNER JOIN reasons ON reasons.id = posts_reasons.reason_id 
WHERE 
    posts.deleted_at IS NOT NULL 
    AND TIMESTAMPDIFF(SECOND, posts.created_at, posts.deleted_at) <= 3600 
GROUP BY 
    TRUNCATE(reasons.weight, -1) 
ORDER BY 
    TRUNCATE(reasons.weight, -1) ASC; 

爲了進一步聚集通過聚合值,您可以使用子查詢:

SELECT 
    ReasonsWeight 
    , AVG(TimeToDeletion) AS AvgTimeToDeletion 
    , COUNT(*) AS PostCount 
FROM 
    (
    SELECT 
     TRUNCATE(SUM(reasons.weight), -1) AS ReasonsWeight, 
     MIN(TIMESTAMPDIFF(SECOND, posts.created_at, posts.deleted_at)) AS TimeToDeletion -- This is per post ID here, aggregation does not matter 
    FROM 
     posts 
     INNER JOIN posts_reasons ON posts_reasons.post_id = posts.id 
     INNER JOIN reasons ON reasons.id = posts_reasons.reason_id 
    WHERE 
     posts.deleted_at IS NOT NULL AND 
     TIMESTAMPDIFF(SECOND, posts.created_at, posts.deleted_at) <= 3600 
    GROUP BY 
     posts.id 
) AS SRC 
GROUP BY 
    ReasonsWeight 
ORDER BY 
    ReasonsWeight ASC 
; 
+0

但是我正在尋找的10組*總*理由重量(即權重的原因的總和),而不是個人重量。 – ArtOfCode

+0

然後使用子查詢。那裏有一個更新 – Pred