gpt4 book ai didi

sql - 将表转换为单列值的单热编码

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

我有一个包含两列的表格:

+---------+--------+
| keyword | color |
+---------+--------+
| foo | red |
| bar | yellow |
| fobar | red |
| baz | blue |
| bazbaz | green |
+---------+--------+

我需要在 PostgreSQL 中进行某种单热编码和转换表以:

+---------+-----+--------+-------+------+
| keyword | red | yellow | green | blue |
+---------+-----+--------+-------+------+
| foo | 1 | 0 | 0 | 0 |
| bar | 0 | 1 | 0 | 0 |
| fobar | 1 | 0 | 0 | 0 |
| baz | 0 | 0 | 0 | 1 |
| bazbaz | 0 | 0 | 1 | 0 |
+---------+-----+--------+-------+------+

是否可以只使用 SQL?关于如何开始的任何提示?

最佳答案

如果我理解正确,你需要条件聚合:

select keyword,
count(case when color = 'red' then 1 end) as red,
count(case when color = 'yellow' then 1 end) as yellow
-- another colors here
from t
group by keyword

关于sql - 将表转换为单列值的单热编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45621338/

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