首页 > 解决方案 > CASE 语句和 GROUP BY 子句中的聚合函数错误

问题描述

我在更大的查询中使用了以下 CTE,并且根据我的分组方式收到了两条不同的错误消息。

我正在使用 Redash 并使用 Amazon Athena。我可以按tenant_id 分组,也可以按tenant_id& 我的 case 语句分组"active"。无论哪种方式,我都会收到错误消息。

active_billpay AS
  (SELECT o.tenant_id as tenant_id, CASE WHEN o.created_date >= min(mbpc.created_date) 
     THEN true else false end as active
    FROM reporting.t_order o
    LEFT JOIN reporting.t_me_bill_pay_charge mbpc ON o.tenant_id = mbpc.tenant_id
      WHERE o.retired_date is null
        AND mbpc.retired_date is null
    GROUP by 1),

如果我只按tenant_id 分组:

运行查询时出错:SYNTAX_ERROR: line 13:32: '(CASE WHEN ("o"."created_date" >= "min"("mbpc"."created_date")) THEN true ELSE false END)' 必须是聚合表达式或出现在 GROUP BY 子句中

如果我同时按tenant_id 和活动分组:

运行查询时出错:SYNTAX_ERROR:第 13:32 行:GROUP BY 子句不能包含聚合或窗口函数:["min"("mbpc"."created_date")]

先感谢您。

标签: sqlprestoamazon-athenaredash

解决方案


我认为您只想通过tenant_idand聚合created_date

 SELECT o.tenant_id as tenant_id,
        (CASE WHEN o.created_date >= MIN(mbpc.created_date) THEN true ELSE false
         END) as active
 FROM reporting.t_order o LEFT JOIN
      reporting.t_me_bill_pay_charge mbpc
      ON o.tenant_id = mbpc.tenant_id
 where o.retired_date is null
 and mbpc.retired_date is null
 group by o.tenant_id, o.created_date

推荐阅读