Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL to get result from one query as columns to another query

Tags:

sql

postgresql

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.

like image 890
Some programmer dude Avatar asked Sep 05 '25 18:09

Some programmer dude


2 Answers

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.

like image 179
Victor Sergienko Avatar answered Sep 08 '25 12:09

Victor Sergienko


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
like image 41
Andriy M Avatar answered Sep 08 '25 12:09

Andriy M