gpt4 book ai didi

sql - 从 Redshift 中的组中选择一个随机属性

转载 作者:行者123 更新时间:2023-11-29 14:00:31 25 4
gpt4 key购买 nike

我在表单中有一个数据集。

id  |   attribute
-----------------
1 | a
2 | b
2 | a
2 | a
3 | c

期望的输出:

attribute|  num
-------------------
a | 1
b,a | 1
c | 1

在 MySQL 中,我会使用:

select attribute, count(*) num 
from
(select id, group_concat(distinct attribute) attribute from dataset group by id) as subquery
group by attribute;

我不确定这可以在 Redshift 中完成,因为它不支持 group_concat 或任何 psql 组聚合函数,如 array_agg() 或 string_agg()。参见 this question .

另一个可行的解决方案是,如果有一种方法可以让我从每个组中选择一个随机属性而不是 group_concat。这在 Redshift 中如何工作?

最佳答案

我找到了一种方法来为每个 ID 选取一个随机属性,但这太棘手了。其实我认为这不是一个好方法,但它确实有效。

SQL:

-- (1) uniq dataset 
WITH uniq_dataset as (select * from dataset group by id, attr)
SELECT
uds.id, rds.attr
FROM
-- (2) generate random rank for each id
(select id, round((random() * ((select count(*) from uniq_dataset iuds where iuds.id = ouds.id) - 1))::numeric, 0) + 1 as random_rk from (select distinct id from uniq_dataset) ouds) uds,
-- (3) rank table
(select rank() over(partition by id order by attr) as rk, id ,attr from uniq_dataset) rds
WHERE
uds.id = rds.id
AND
uds.random_rk = rds.rk
ORDER BY
uds.id;

结果:

 id | attr
----+------
1 | a
2 | a
3 | c

OR

id | attr
----+------
1 | a
2 | b
3 | c

这是此 SQL 中的表。

-- dataset (original table)
id | attr
----+------
1 | a
2 | b
2 | a
2 | a
3 | c

-- (1) uniq dataset
id | attr
----+------
1 | a
2 | a
2 | b
3 | c

-- (2) generate random rank for each id
id | random_rk
----+----
1 | 1
2 | 1 <- 1 or 2
3 | 1

-- (3) rank table
rk | id | attr
----+----+------
1 | 1 | a
1 | 2 | a
2 | 2 | b
1 | 3 | c

关于sql - 从 Redshift 中的组中选择一个随机属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21084913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com