我在PostgreSQL中有这个查询
SELECT numeric_value, entity_id
FROM data_value
WHERE
entity_id = 16029 OR
entity_id = 16026 OR
entity_id = 33768 AND
category_id = 158
对我来说重要的是数值,但我希望以这种格式显示:
16029 | 16026 | 33768
value | value | value
value | value | value
这有可能吗?或者它有效吗?因为我必须在非常慢的服务器上工作,我想尽可能地进行优化。
答案 0 :(得分:2)
应该可以使用crosstab函数创建该结果。
不是Postgres中最简单的部分,所以要准备花些时间阅读文档并进行实验:)
我认为从doc开始并不是很明显:tablefunc是包含交叉表的扩展。默认情况下不会安装扩展程序,请使用CREATE EXTENSION
进行安装。
答案 1 :(得分:1)
您是否错过了查询中的括号,如果是这样的话:
select
numeric_value, entity_id
from data_value
where
entity_id in (16029, 16026, 33768) and
category_id = 158
无论如何,您可以使用聚合轻松地手动转移数据(如果您想要获得多行,则只需指定密钥,从您的问题中不清楚如何将值组合在一起):
select
--<some key>,
max(case when entity_id = 16029 then numeric_value end) as 16029,
max(case when entity_id = 16026 then numeric_value end) as 16026,
max(case when entity_id = 33768 then numeric_value end) as 33768
from data_value
where
entity_id in (16029, 16026, 33768) and
category_id = 158
--group by <some key>
答案 2 :(得分:0)
也许是这样的?
select
a.value,
b.value,
c.value
from
(select numeric_value as value from data_value where entity_id=16029 AND category_id =158) a,
(select numeric_value as value from data_value where entity_id=16026 AND category_id =158) b,
(select numeric_value as value from data_value where entity_id =33768 AND category_id =158) c