sql
  • postgresql
  • group-by
  • 2016-09-22 151 views 0 likes 
    0

    當我運行此查詢列「ic.inscount」必須出現在GROUP BY子句或聚合函數中使用

    WITH install_count_join_date AS (
        SELECT 
        date_trunc('month', join_date) AS date, 
        COUNT(*) AS "inscountjoin" 
        FROM 
        apps202_prod.search 
        WHERE 
        join_date >= '2016-06-01' 
        AND 
        app_id = 3 
        GROUP BY 
        date_trunc('month', join_date) 
    ), install_count AS (
        SELECT 
        DATE(original_timestamp) AS date, 
        COUNT(*) AS "inscount" 
        FROM 
        apps202_prod.search 
        WHERE 
        original_timestamp >= '2016-06-01' 
        AND 
        app_id = 3 
        GROUP BY 
        DATE(original_timestamp) 
    ) 
    
    SELECT 
        date_trunc('month', mr.date) AS "money_revenue_date", 
        SUM(mr.amount) AS "amt", 
        ic.inscount AS "install_count" 
    FROM 
        mysql_apps202_prod.apps202_prod_money_revenue mr 
        join install_count ic on date_trunc('month', ic.date) = date_trunc('month', mr.date) 
    WHERE 
        date_trunc('month', mr.date) >= '2016-06-01' 
    AND 
        mr.app_id = 3 
    
    GROUP BY 
        date_trunc('month', mr.date) 
    

    我得到這個錯誤:

    column ic.inscount must appear in the GROUP BY clause or be used in an aggregate function

    +1

    該錯誤是相當自我解釋...因爲你的最終查詢使用聚合('sum'),您需要將其他字段添加到'組by'子句... – sgeddes

    +0

    我不需要爲該組添加子帳號,因爲我已經在with子句中彙總了它,因爲您在上面的代碼中看到它 –

    +0

    您正在彙總外部查詢中的「amount」列。所以是的,你必須再次使用'group by'(對於這兩個字段)... – sgeddes

    回答

    0

    你必須改變你的select語句如下,因爲你有很多關於你正在處理的問題的反饋,如果你正在使用group,那麼你選擇除了group by之外的所有具有聚合函數的列。在你的情況ic.inscount既不分組也不使用任何聚合函數,所以請根據您的要求使用下面的一個。

    SELECT 
        date_trunc('month', mr.date) AS "money_revenue_date", 
        SUM(mr.amount) AS "amt", 
        ic.inscount AS "install_count" 
    FROM mysql_apps202_prod.apps202_prod_money_revenue mr 
    join install_count_join_date ic on date_trunc('month', ic.date) = date_trunc('month', mr.date) 
    WHERE date_trunc('month', mr.date) >= '2016-06-01' 
        AND mr.app_id = 3 
    GROUP BY date_trunc('month', mr.date), ic.inscount 
    

    OR

    SELECT 
        date_trunc('month', mr.date) AS "money_revenue_date", 
        SUM(mr.amount) AS "amt", 
        MAX(ic.inscount) AS "install_count" --Any Addregate Function 
    FROM mysql_apps202_prod.apps202_prod_money_revenue mr 
    join install_count_join_date ic on date_trunc('month', ic.date) = date_trunc('month', mr.date) 
    WHERE date_trunc('month', mr.date) >= '2016-06-01' 
        AND mr.app_id = 3 
    GROUP BY date_trunc('month', mr.date) 
    
    +0

    有一個錯誤「關係」install_count「不存在」 –

    +0

    你錯過了CTE在查詢中使用,所以讓我解決這個問題,如果我沒有錯,你想使用CTE全名'install_count_join_date'而不是'INSTALL_COUNT'。嘗試使用上面的更新代碼 – Susang

    相關問題