Question

I have this query in 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

The important thing to me is the numeric value, but I would like to display in this format:

16029 | 16026 | 33768
value | value | value
value | value | value

Is this possible somehow? Or it's effective? Because I have to work on a very slow server and I want to optimize as well as possible.

Était-ce utile?

La solution 2

Have you missed parenthesis in your query, should it be something like this:

select
    numeric_value, entity_id
from data_value
where
    entity_id in (16029, 16026, 33768) and
    category_id = 158

Anyway, you can easily pivot data by hand with aggregates (you just have to specify key if you want to get more than one row, it's not clear from your question how values should be grouped together):

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>

Autres conseils

Should be possible to create that result using the crosstab function.

Not the easiest part of Postgres, so be prepared to spend some time reading the docs and experimenting :)

As I think it's not immediately obvious from the doc: tablefunc is the extension containing crosstab. Extensions are not installed by default, use CREATE EXTENSION to install them.

Maybe something like this?

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 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top