2

我在 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

这有可能吗?还是有效?因为我必须在一个非常慢的服务器上工作,并且我想尽可能地优化。

4

3 回答 3

2

应该可以使用交叉表函数创建该结果。

这不是 Postgres 中最简单的部分,因此请准备好花一些时间阅读文档并进行实验 :)

正如我认为从文档中看不到的那样:tablefunc 是包含交叉表的扩展。默认情况下不安装扩展,使用CREATE EXTENSION来安装它们。

于 2013-10-11T20:24:07.137 回答
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>
于 2013-10-12T06:50:49.687 回答
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 
于 2013-10-11T20:47:07.693 回答