2017-08-10 26 views
0

我有两列的表:变换表热编码一个单独列的值的

+---------+--------+ 
| 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?有关如何开始的任何提示?

+0

是什么'一个热encoding'是什么意思? – Siyual

+1

是你的名单“颜色”已知的前? –

+0

@ PM77-1是的,只有那四个。 – Ernest

回答

3

如果我理解正确的,你需要有条件聚集:

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 
+0

不知道为什么这是downvoted,它确实的工作。看起来如此明显,谢谢。 – Ernest

+0

不客气。 –

相关问题