Avoid nested aggregate error using coalesce()

浪子不回头ぞ 提交于 2020-07-03 13:41:27

问题


I currently have a query using coalesce that worked in SQL server,however, it is not working in Amazon Redshift. Is there a way I can more appropriately write this to use in Redshift:

    coalesce(sum(Score)/nullif(sum(ScorePrem),0),0) as percent

回答1:


Consider running the aggregate query as a subquery or CTE, then handle transformation or secondary calculations in an outer main query.

WITH agg AS (
  SELECT calendar_month_id
         ,day_of_month
         ,month_name
         ,DaysRemaining
         ,RPTBRANCH
         ,0 AS TotalGrp
         ,SUM(Score) AS Score
         ,SUM(ScorePrem) AS ScorePrem
  FROM #temp_Score
  GROUP BY calendar_month_id
         , day_of_month
         , month_name
         , DaysRemaining
         , RPTBranch
)

SELECT calendar_month_id
       ,day_of_month
       ,month_name
       ,DaysRemaining
       ,RPTBRANCH
       ,TotalGrp
       ,Score
       ,ScorePrem
       ,COALESCE(Score/NULLIF(ScorePrem,0),0) AS percent
FROM agg


来源:https://stackoverflow.com/questions/62416808/avoid-nested-aggregate-error-using-coalesce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!