2

我在更大的查询中使用了以下 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")]

先感谢您。

4

2 回答 2

2

我认为您只想通过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
于 2019-06-07T17:12:52.757 回答
0

为了应用聚合函数min,SQL 要求您非常具体地了解聚合适用的数据集。即使 SQL 允许您编写的查询,您仍然只能获得created_date每行的最小值,而不是每个tenant_id.

为了做我认为您正在尝试做的事情,您应该使用子查询来获取created_dateeach的最小值tenant_id,然后使用该值通知您的active字段。

SELECT o.tenant_id AS tenant_id,
       CASE WHEN o.created_date >= min_created_date THEN TRUE ELSE FALSE END AS active
FROM   reporting.t_order o
       LEFT JOIN
       (SELECT tenant_id, MIN (created_date) AS min_created_date
        FROM   reporting.t_me_bill_pay_charge
        WHERE  retired_date IS NULL) mbpc
           ON o.tenant_id = mbpc.tenant_id
WHERE  o.retired_date IS NULL

通常,如果您发现自己试图通过执行类似的操作来欺骗 SQL 语法要求group by 1,则强烈表明您的方法存在缺陷。

于 2019-06-07T17:21:22.820 回答