如何在新表的多行中从同一行插入不同的值

时间:2016-05-24 07:39:48

标签: sql postgresql

我有A表:

id bigint,
a integer,
b integer,
c integer,
date date

我必须将每个值放在一个新表后面的日期,这样:

B table:
id bigint,
type integer,
date date

例如,如果在我的A表中我有这样一行:

id a b c date
13 5 4 7 2014-11-09

我想将这些值放在B表中,如下所示:

id type date
1  5    2014-11-09,
2  4    2014-11-09,
3  7    2014-11-09

有什么建议吗?

4 个答案:

答案 0 :(得分:1)

使用import numpy as np x = np.linspace(0,25,101) #x: 101 values between 0 and 25 y = x**2/20 x[y>30] #filter output: [ 24.5 , 24.75, 25. ] y[y>30] #filter output: [ 30.0125 , 30.628125, 31.25 ] 取消首先取消数据,然后使用UNION ALL分配新的id

ROW_NUMBER

如果新生成的SELECT ROW_NUMBER() OVER(ORDER BY id, col) AS id, type, date FROM ( SELECT id, 'a' AS col, a AS type, date FROM tableA UNION ALL SELECT id, 'b' AS col, b AS type, date FROM tableA UNION ALL SELECT id, 'c' AS col, c AS type, date FROM tableA ) t 是自动生成的,则根本不需要id

ROW_NUMBER

答案 1 :(得分:0)

INSERT  INTO A
    ( id ,
      a ,
      b ,
      c ,
      date )
VALUES  ( 13,
      5 ,
      4 ,
      7 ,
      2014-11-09
    )



ALTER TRIGGER NewTrigger ON A
AFTER INSERT
AS
BEGIN  
    SET NOCOUNT ON;


    DECLARE @id AS NVARCHAR(50)
    DECLARE @type AS NVARCHAR(50)
    DECLARE @date AS INT



    SELECT  @Date = INSERTED.Date
    FROM    INSERTED


    INSERT  INTO B
            ( Date,
              Type,
              id
            )
    VALUES  ( @Date,
              4,
              1 
            )

END
GO

SELECT  * A
SELECT  * FROM  B

答案 2 :(得分:0)

在Oracle中,您可以尝试使用REGEXP来模拟sqame。希望这会有所帮助。

SELECT DISTINCT LEVEL,
  TRIM(regexp_substr(a.colk,'[^,]+', 1, level)) TYPE,
  SYSDATE
FROM
  (SELECT LEVEL,
    COL1
    ||','
    ||COL2
    ||','
    ||COL3 colk,
    SYSDATE
  FROM
    (SELECT 13 AS ID,5 COL1,4 AS COL2,7 AS COL3,sysdate AS dt FROM DUAL
    )
    CONNECT BY LEVEL <= REGEXP_COUNT(COL1
    ||','
    ||COL2
    ||','
    ||COL3,',')+1
  )a
  CONNECT BY regexp_substr(a.colk, '[^,]+', 1, level) IS NOT NULL;

答案 3 :(得分:0)

竞赛最短代码:)我的变体是:

insert into b(type, date)
select unnest(array[a,b,c]), date from a;

假设id表中的b列是自动增量的。