问题
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