Athena row_number 函数与 where 或 count 结合使用
Athena row_number function using in combination with where or count
这里有点新手,正在努力掌握应该是基本任务的东西。
我有一个简单的 table 产品,其中许多产品有多种颜色。我想知道有多少产品具有三种以上的颜色。
我从下面的内容开始:
SELECT product_colour,
product_id,
row_number() over (partition by product_colour) AS row_num
FROM table
WHERE row_num > 3
ORDER BY product_id
上面没有工作,因为 SQL 中的 outer/inner 逻辑,之前用谷歌搜索过,所以很可能会误解。
我按照教程进行了尝试。
SELECT rn,
product_colour,
product_id,
FROM
(
SELECT row_number() over (partition by product_colour ORDER BY product_colour) AS rn,
product_colour,
product_id,
FROM table
) AS t
HAVING COUNT(t.rn) > 3
无论使用何种语法组合 "stuff" 我都希望通过此错误消息“'"rn"' 必须是聚合表达式或出现在 GROUP BY 子句中”。我根本做不到。
受到第一响应者的启发,我设法得到了最接近的,但是,这个查询不再 returns 任何错误消息,只是一个空的 table。
SELECT product_colour,
t.rn,
product_id,
FROM
(
SELECT row_number() over (partition by product_colour) AS rn,
product_colour,
product_id
FROM table
) AS t
GROUP BY product_colour, product_id, t.rn
HAVING COUNT(t.rn) > 3
ORDER BY product_colour, t.rn
有什么想法吗?
如果您想要包含 3 种或更多颜色的产品列表,不需要 window 函数,您可以只使用聚合:
select product_id
from mytable
group by product_id
having count(distinct product_colour) >= 3
如果您想知道有多少产品有更多3种颜色或更多,那么您可以添加另一个聚合级别:
select count(*)
from (
select 1
from mytable
group by product_id
having count(distinct product_colour) >= 3
) t
注意:如果 (product_id, product_colour)
类型在您的 table 中是唯一的,则不需要 distinct
。
这里有点新手,正在努力掌握应该是基本任务的东西。
我有一个简单的 table 产品,其中许多产品有多种颜色。我想知道有多少产品具有三种以上的颜色。
我从下面的内容开始:
SELECT product_colour,
product_id,
row_number() over (partition by product_colour) AS row_num
FROM table
WHERE row_num > 3
ORDER BY product_id
上面没有工作,因为 SQL 中的 outer/inner 逻辑,之前用谷歌搜索过,所以很可能会误解。
我按照教程进行了尝试。
SELECT rn,
product_colour,
product_id,
FROM
(
SELECT row_number() over (partition by product_colour ORDER BY product_colour) AS rn,
product_colour,
product_id,
FROM table
) AS t
HAVING COUNT(t.rn) > 3
无论使用何种语法组合 "stuff" 我都希望通过此错误消息“'"rn"' 必须是聚合表达式或出现在 GROUP BY 子句中”。我根本做不到。
受到第一响应者的启发,我设法得到了最接近的,但是,这个查询不再 returns 任何错误消息,只是一个空的 table。
SELECT product_colour,
t.rn,
product_id,
FROM
(
SELECT row_number() over (partition by product_colour) AS rn,
product_colour,
product_id
FROM table
) AS t
GROUP BY product_colour, product_id, t.rn
HAVING COUNT(t.rn) > 3
ORDER BY product_colour, t.rn
有什么想法吗?
如果您想要包含 3 种或更多颜色的产品列表,不需要 window 函数,您可以只使用聚合:
select product_id
from mytable
group by product_id
having count(distinct product_colour) >= 3
如果您想知道有多少产品有更多3种颜色或更多,那么您可以添加另一个聚合级别:
select count(*)
from (
select 1
from mytable
group by product_id
having count(distinct product_colour) >= 3
) t
注意:如果 (product_id, product_colour)
类型在您的 table 中是唯一的,则不需要 distinct
。