我在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
这有可能吗?还是有效?因为我必须在一个非常慢的服务器上工作,我希望尽可能优化。
最佳答案
您的查询中是否遗漏了括号,应该是这样的:
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>
关于sql - sql列的字段值-有可能吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19326585/