简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM