开发者

Generating the unique sets of attributes into a new table?

I currently need to make a table that holds the unique sets of attributes for another table. That is, I have a table that looks like this:

Table A : col开发者_高级运维umns = col 1, col2, col3, col4, col5

And I need to produce this:

Table B : columns = columnName, value
col 1, col1attribute1
col 1, col1attribute2
col 1, col1attribute3
col 2, col2attribute1
col 3, col3attribute1
col 3, col3attribute2

Is there an easy way to do this with (PL)SQL alone? It seems simple enough if I do it programatically in Java, but ideally I'd like an sql-only solution if possible.


The following seems to work:

CREATE TABLE TABLE_B (COLUMN_NAME, VALUE) AS
  SELECT DISTINCT 'COL_1', COL_1 FROM TABLE_A
  UNION ALL
  SELECT DISTINCT 'COL_2', COL_2 FROM TABLE_A
  UNION ALL
  SELECT DISTINCT 'COL_3', COL_3 FROM TABLE_A
  UNION ALL
  SELECT DISTINCT 'COL_4', COL_4 FROM TABLE_A
  UNION ALL
  SELECT DISTINCT 'COL_5', COL_5 FROM TABLE_A;

Share and enjoy.


Another way is to use:

  SELECT * INTO table_b from (
  SELECT DISTINCT 'COL_1', COL_1 FROM TABLE_A
  UNION ALL
  SELECT DISTINCT 'COL_2', COL_2 FROM TABLE_A
  UNION ALL
  SELECT DISTINCT 'COL_3', COL_3 FROM TABLE_A
  UNION ALL
  SELECT DISTINCT 'COL_4', COL_4 FROM TABLE_A
  UNION ALL
  SELECT DISTINCT 'COL_5', COL_5 FROM TABLE_A)a;

EDIT: as someone points out this works in postgres, (and I think sql server as well), from your PL/SQL tag, I assumed postgres as postegres is PL/pgSQL, hadn't noticed that until now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜