Suppose the PostgreSQL table structure looks like the following:
Time | Name | Value
w | d | 0
x | a | 1
x | b | 2
y | c | 3
y | b | 4
z | c | 5
z | a | 6
z | d | 7
I have the need of displaying the data as follows:
Time | Name A | Name B | Name C |
x | 1 | 2 | |
y | | 4 | 3 |
z | 6 | | 5 |
The number of Name variables is undefined and unknown prior to the query and the only filtering that is done is by Time. The table's row count goes into the millions and time is crucial. In other words, the user, at request time, is able to dynamically select the Name variables he/she wants to see displayed on the result as well as the Time range to filter by.
The approach I currently have implemented generates a dynamic query in real-time as the request comes in that looks like the following:
WITH SubQuery AS(
SELECT "Name", "Time", "Value"
FROM "Table"
WHERE "Name" IN ('a','b','c') AND "Time" BETWEEN 'x' AND 'z'
ORDER BY "Time" ASC
)
SELECT ("MasterTime") as "Time", "Name A","Name B","Name C"
FROM (
SELECT "Time" as "MasterTime"
FROM SubQuery
) AS "TimeData" FULL OUTER JOIN (
SELECT "Time" as "Time'A'", "Value" as "Name A"
FROM SubQuery WHERE "Name" = 'a'
) AS "Data'A'" ON "MasterTime"="Time'A'" FULL OUTER JOIN (
SELECT "Time" as "Time'B'", "Value" as "Name B"
FROM SubQuery WHERE "Name" = 'b'
) AS "Data'B'" ON "MasterTime"="Time'B'" FULL OUTER JOIN (
SELECT "Time" as "Time'C'", "Value" as "Name C"
FROM SubQuery WHERE "Name" = 'c'
) AS "Data'C'" ON "MasterTime"="Time'C'"
ORDER BY "MasterTime" ASC
I was thinking this may be a common issue in the world of data basing and there probably is a better solution out there. All suggestions are welcome.