Lets say I have these two tables:
CREATE TABLE nodes
(
id INTEGER PRIMARY KEY,
name TEXT
);
CREATE TABLE events
(
id INTEGER PRIMARY KEY,
node INTEGER REFERENCES nodes,
etime TIMESTAMP,
value TEXT
);
Is there a query to get the values from the nodes
table as columns to the events
table?
For a simple example I would like something like this:
node1 | node2 | node3
-------+--------+--------
event1 | |
| event2 |
| | event3
Is this possible?
What I really would like, would be an SQL query that could output something like this:
etime | node1 | node2 | node3
--------------------+---------+---------+--------
2011-04-26 13:12:23 | Event 1 | | Event 2
2011-04-26 15:52:43 | | Event 3 |
2011-04-26 21:35:12 | Event 4 | Event 5 | Event 6
Where node1
to node3
comes from the node
table, and the timestamps and Event
texts comes from the events
table.
This is called crosstab or pivot query, and there is no SQL-compliant way to generate one.
Quick googling says there's a contrib module for PostgreSQL (looks like in core now).
Another pretty interesting blog post here (first in google) - though it's not fully crosstab, as it has fixed number of columns.
Use grouping and aggregating on CASE expressions:
SELECT
e.etime,
MIN(CASE n.name WHEN 'node1' THEN e.value END) AS node1,
MIN(CASE n.name WHEN 'node2' THEN e.value END) AS node2,
MIN(CASE n.name WHEN 'node3' THEN e.value END) AS node3
FROM events e
INNER JOIN nodes n ON e.node = n.id
GROUP BY
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With