【问题标题】:Avoid nested aggregate error using coalesce()使用 coalesce() 避免嵌套聚合错误
【发布时间】:2020-06-16 20:10:36
【问题描述】:

我目前有一个使用合并的查询,该查询在 SQL Server 中有效,但在 Amazon Redshift 中无效。有没有办法我可以更合适地写这个在 Redshift 中使用:

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

【问题讨论】:

  • coalesce替换nullif
  • 您得到的结果有什么问题?如果您遇到错误,请分享实际的错误消息。
  • @zealous 它表明不允许嵌套聚合调用。我尝试替换 nullif,但这也没有帮助。有什么想法吗?
  • @a_horse_with_no_name 请查看已编辑的查询帖子。这是版本 PostgreSQL 8.0.2 和 Redshift 1.0.16496
  • 嗯,Redshift 不是 Postgres。

标签: sql null aggregate amazon-redshift coalesce


【解决方案1】:

考虑将聚合查询作为子查询或 CTE 运行,然后在外部主查询中处理转换或辅助计算。

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

【讨论】:

  • 只是好奇我的选择与它一起会是什么样子?我似乎无法让它工作。感谢您的帮助!
  • 将您的原始查询放在 CTE 中,然后使用最终表达式选择所需的列。见编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多