我有一个包含两列的表:
+---------+--------+
| 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?如何入门有什么建议吗?
发布于 2017-08-11 02:49:49
如果我没理解错的话,你需要条件聚合:
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发布于 2019-05-09 21:21:57
要在包含大量列的表上使用此代码,请使用Python生成查询:
1)创建一个列表,其中包含您希望作为列名的唯一变量,并将其导入Python,例如:list。
for item in list:
print('count(case when item=' +str(item)+ 'then 1 end) as is_'+str(item)+',')2)复制输出(减去最后一行的最后一个逗号)
3)然后:
select keyword,
OUTPUT FROM PYTHON
from t
group by keyword发布于 2019-09-13 21:28:29
在测试用例中使用tablefunc扩展和COALESCE() to fill all NULL fields实现该目标的另一种方法
postgres=# create table t(keyword varchar,color varchar);
CREATE TABLE
postgres=# insert into t values ('foo','red'),('bar','yellow'),('fobar','red'),('baz','blue'),('bazbaz','green');
INSERT 0 5
postgres=# SELECT keyword, COALESCE(red,0) red,
COALESCE(blue,0) blue, COALESCE(green,0) green,
COALESCE(yellow,0) yellow
FROM crosstab(
$$select keyword, color, COALESCE('1',0) as onehot from test01
group by 1, 2 order by 1, 2$$,
$$select distinct color from test01 order by 1$$)
AS result(keyword varchar, blue int, green int, red int, yellow int);
keyword | red | blue | green | yellow
---------+-----+------+-------+--------
bar | 0 | 0 | 0 | 1
baz | 0 | 1 | 0 | 0
bazbaz | 0 | 0 | 1 | 0
fobar | 1 | 0 | 0 | 0
foo | 1 | 0 | 0 | 0
(5 rows)
postgres=# 如果你只是想在psql下获得结果
postgres=# select keyword, color, COALESCE('1',0) as onehot from t
--group by 1, 2 order by 1, 2
\crosstabview keyword color
keyword | red | yellow | blue | green
---------+-----+--------+------+-------
foo | 1 | | |
bar | | 1 | |
fobar | 1 | | |
baz | | | 1 |
bazbaz | | | | 1
(5 rows)
postgres=# https://stackoverflow.com/questions/45621338
复制相似问题