我在大型查询中使用以下CTE,并且根据分组方式,我收到两条不同的错误消息。
我正在使用Redash并正在使用Amazon Athena。我可以按tenant_id分组,也可以按tenant_id
和名为"active"
的case语句进行分组。无论哪种方式,我都会收到错误消息。
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:第13:32行:'(情况为 (“ o”。“ created_date”> =“ min”(“ mbpc”。“ created_date”))然后为真 false END)'必须为聚合表达式或出现在GROUP BY中 条款
如果我同时按tenant_id和active分组:
错误运行查询:SYNTAX_ERROR:行13:32:GROUP BY子句不能 包含集合或窗口函数: [“ min”(“ mbpc”。“ created_date”)]
谢谢。
答案 0 :(得分:2)
我认为您只想按tenant_id
和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
答案 1 :(得分:0)
为了应用诸如min
之类的聚合函数,SQL要求您非常具体地说明将聚合应用于哪些数据集。即使SQL允许您编写的查询,您仍然只会为每行(而不是每一个created_date
)获得最小的tenant_id
。
为了执行我认为您要尝试执行的操作,应使用子查询来获取每个created_date
的最小值tenant_id
,然后使用该值通知您的{{1 }}字段。
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语法要求,则表明该方法存在缺陷。