Domanda

I have the following table:

 |fk ID|value | val id|
 |  1  | val11|  1    |
 |  1  | val12|  2    |
 |  2  | val21|  1    |
 |  2  | val22|  2    |

I want to transpose it to:

 | fk ID | val1Title | val2Title |
 | 1     | val11     | val12     |
 | 2     | val21     | val22     |

Ive added an ID column to the top table which is used to order so we know that val11 is in the first column because it has an id less that val12.

I have an oracle DB and I think I need to pivot. I've found a couple of articles on it (e.g. Transposing Table) although it seems to be a lot of work for the pivot. Is this the easiest way?

How can I easily transpose? Im using Oracle 11g so am happy to use Oracle specific functions. I've used ListAgg but that combines the columns. I want to columns separate though.

EDIT: The design of the original table is not normalised at the moment because this is actually the result of quite a complicated query.

È stato utile?

Soluzione

You can do an old-school pivot

SELECT fk_ID,
       MAX(CASE WHEN val_id=1 THEN value ELSE null END) as Val1Title,
       MAX(CASE WHEN val_id=2 THEN value ELSE null END) as Val2Title
  FROM table_name
 GROUP BY fk_ID

In 11g, you can also use the PIVOT keyword

SELECT fk_id,
       "1_VAL" as Val1Title,
       "2_VAL" as Val2Title
  FROM table_name
 PIVOT( MAX(value) as val for (val_id) in (1,2))

See this sqlfiddle for an example

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top