我正在尝试使用 athena 查询按小时获取 CloudFront 分配的请求数。
我在 this Link 的指导下创建了 cloudfront_logs 表在我的 sample_db 中
以下是我为按小时获取请求数而进行的查询
SELECT date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))) as TIME, count(*) as CNT
FROM "sample_db"."cloudfront_logs"
WHERE
from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) >= from_iso8601_timestamp('2019-05-29T00:00:00')
AND
from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) < from_iso8601_timestamp('2019-05-30T00:00:00')
GROUP BY TIME
ORDER BY TIME ASC;
但是它返回这样的错误
SYNTAX_ERROR: line 2:8: '"date_trunc"('hour', "from_iso8601_timestamp"("concat"("concat"("date_format"("date", '%Y-%m-%d'), 'T'), "time")))' must be an aggregate expression or appear in GROUP BY clause
因此,我更换了
TIME
之后 GROUP BY
至 date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)))
,并再次尝试。SELECT date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))) as TIME, count(*) as CNT
FROM "sample_db"."cloudfront_logs"
WHERE
from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) >= from_iso8601_timestamp('2019-05-29T00:00:00')
AND
from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)) < from_iso8601_timestamp('2019-05-30T00:00:00')
GROUP BY date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time)))
ORDER BY TIME ASC;
最后,我得到了结果。
我认为,它也应该适用于第一个查询。我可以就第一次查询获得任何建议吗?因为它看起来更简单。
最佳答案
Athena 基于 Presto。在 Presto 中,您不能使用 SELECT
GROUP BY
中的子句列别名条款。
但是,您可以使用相同的表达式,例如:
SELECT some_expression(a) FROM ... GROUP BY some_expression(a)
另外,您可以引用
SELECT
子句列使用它们在 SELECT 列表中的位置:SELECT some_expression(a) FROM ... GROUP BY 1
这是 ANSI SQL 标准语法。见 Presto GROUP BY documentation了解模式详情。
这可以在
ORDER BY
中使用同样,所以您的查询将类似于SELECT date_trunc('hour',from_iso8601_timestamp(concat(concat(date_format(date, '%Y-%m-%d'), 'T'), time))) as TIME, count(*) as CNT
FROM "sample_db"."cloudfront_logs"
WHERE ...
GROUP BY 1
ORDER BY 1 ASC;
关于sql - 如何使用 'must be an aggregate expression or appear in GROUP BY clause' 子句修复 'as',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56390966/