I have the following table:
id | name
1 | Group1
2 | Group2
.. | ...
I want to join it with another table this way:
id | group_1 | group_2 | ..
1 | 10 | 8 | ..
2 | 12 | 6 | ..
Hence Group1
with id 1
will be joined with the 2nd table group_1
.
To group the columns and avoid:
id | group_id | value
1 | 1 | 10
2 | 1 | 12
3 | 2 | 8
4 | 2 | 6
.. | .. | ..
Is it possible or is there an alternative way to achive the same result?
2
Answers
What you’re doing is often called an unpivot.
Where I write
...
above, you would need to write one additional line like the lines above it (beginning withWHEN
), for each distinct group id, which I infer from your example corresponds to the additional columns of your second table.In general, SQL requires that table names and column names are fixed in the query at the time it is prepared. There’s no way to base an expression dynamically on the values read during query execution.
You can use
CASE
as shown above as a kind of branching construct, so a different sub-expression is used depending on matching specific values.But this requires that you know all the values up front, so you can format the
CASE
expression. Each value must be listed explicitly.If you don’t know the values in advance, then you can’t do this in a single query. You can’t make a query that dynamically adds more terms to an expression depending on the values it reads during execution.
Let’s create groups table:
Let’s create group values table:
Answer: