代码之家  ›  专栏  ›  技术社区  ›  Stefan Kendall

将唯一的属性集生成到新表中?

  •  1
  • Stefan Kendall  · 技术社区  · 14 年前

    我现在需要创建一个表,其中包含另一个表的唯一属性集。也就是说,我有一张这样的桌子:

    Table A : columns = col 1, col2, col3, col4, col5

    我需要制作这个:

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

    单独使用(PL)SQL有简单的方法吗?如果我用Java编程的话,这看起来很简单,但理想情况下,如果可能的话,我想要一个只使用sql的解决方案。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Bob Jarvis - Слава Україні    14 年前

    以下方法似乎有效:

    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;
    

    分享和享受。

        2
  •  0
  •   Mr Shoubs    14 年前

      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;
    

    编辑:正如有人指出这在postgres中有效(我也认为是sql server),从您的PL/sql标记中,我假设postgres作为posteregres是PL/pgSQL,直到现在才注意到这一点。