如何将表从列表转换为布尔值

时间:2019-03-05 09:14:09

标签: postgresql pivot

我在postgresql中有这样的表:

id | item1 | item2  |
1  | book  | pencil |
2  | book  | pencil |
3  | pen   | ruler  |
4  | book  | pen    |

然后我要将其更改为:

id  | book | pencil | pen | ruler |
1   | 1    | 1      | 0   | 0     |
2   | 1    | 1      | 0   | 0     |
3   | 0    | 0      | 1   | 1     |
4   | 1    | 0      | 1   | 0     |

对于true是1,对于false是0

现在查询如何转换它?

1 个答案:

答案 0 :(得分:0)

尝试一下

SELECT 
id, 
COUNT(CASE WHEN (t.item = 'book') THEN 1 ELSE NULL END) AS book, 
COUNT(CASE WHEN (t.item = 'pencil') THEN 1 ELSE NULL END) AS pencil, 
COUNT(CASE WHEN (t.item = 'pen') THEN 1 ELSE NULL END) AS pen, 
COUNT(CASE WHEN (t.item = 'ruler') THEN 1 ELSE NULL END) AS ruler
FROM 
(
SELECT id, item1 AS item FROM test_pivot AS  t1 
UNION ALL 
SELECT id, item2 AS item FROM test_pivot AS t2
) AS t
GROUP BY id