SQL - 将一列插入另一列,而不合并数据

时间:2017-04-21 10:06:01

标签: sql sql-server

搜索线程我只能找到合并或合并,但不能插入和保留原始值。 所以这就是我所拥有的:

ID time1 time2 time3
1   20    NULL  30
2   50    NULL  NULL
2   20    30    40

我需要的是:

ID time
1   20
1   30
2   50
2   20
2   30
2   40

忽略Nulls。 谢谢!

3 个答案:

答案 0 :(得分:4)

select id, time1 as time from your_table where time1 is not null
union all 
select id, time2 from your_table where time2 is not null
union all 
select id, time3 from your_table where time3 is not null

答案 1 :(得分:1)

尝试使用unpivot处理默认值NULL值的比较,并从结果集中排除这些值。

参考目的临时表以及线程

中给出的样本数据
CREATE TABLE #TempTable(
 ID int,
 time1 int, time2 int, time3 int)

 INSERT INTO #TempTable (ID, time1, time2,time3)
  VALUES (1,   20,    NULL,  30), 
  (2,   50,    NULL,  NULL), 
  (2,   20,    30,    40)

此处使用上述临时表数据

  SELECT ID, [time]
  FROM #TempTable
  UNPIVOT
 (
  [time]
 for [timecolumnName] in (time1, time2,time3)
 ) unpiv;

答案 2 :(得分:0)

你只有三列吗?如果只是这样做的话;

INSERT [NewTable]
(Id, time)
SELECT Id, time1
FROM [OldTable]
WHERE time1 IS NOT NULL;

INSERT [NewTable]
(Id, time)
SELECT Id, time2
FROM [OldTable]
WHERE time2 IS NOT NULL;

INSERT [NewTable]
(Id, time)
SELECT Id, time3
FROM [OldTable]
WHERE time3 IS NOT NULL;

如果您可能有三个以上让我们知道 - 您仍然可以使用Dynamic SQL

执行此操作