【问题标题】:How to insert rows from one temp table to another in sql如何在sql中将行从一个临时表插入另一个临时表
【发布时间】:2017-03-08 11:31:56
【问题描述】:
ID LogDate LogTime InoutMode
1 2017-02-23 19:30:00.0000000 1
2 2017-02-23 20:00:00.0000000 0
3 2017-02-23 20:30:00.0000000 1
4 2017-02-23 21:00:00.0000000 0
5 2017-02-23 21:30:00.0000000 1
6 2017-02-24 08:00:00.0000000 0
上面的结果来自一个临时表。现在我想将 LogTime 插入另一个临时表,如下所示。
InOutMode-1 =>InTime
InOutMode-0 =>OutTime
InTime OutTime
19:30:00.0000000 20:00:00.0000000
20:30:00.0000000 21:00:00.0000000
21:30:00.0000000 08:00:00.0000000
【问题讨论】:
标签:
sql
sql-server
stored-procedures
temp-tables
【解决方案1】:
要将一个表的行插入到另一个表中,您可以编写以下 SQL 查询:
INSERT INTO anotherTemp (InTime)
SELECT LogTime
FROM Temp
WHERE InoutMode = 1
INSERT INTO anotherTemp (OutTime)
SELECT LogTime
FROM Temp
WHERE InoutMode = 0
查看此链接了解更多http://www.dofactory.com/sql/insert-into
【解决方案2】:
使用 2 个 cte,一个用于 InoutMode 和 1,另一个用于 0,并且还根据 Id 列或日期和时间列的顺序给出行号。然后加入这 2 个 cte。
查询
;with cte as(
select [rn] = row_number() over(
order by [Id] -- also order by [LogDate], [LogTime]
), *
from #your_temp_table_name
where [InoutMode] = 1
),
cte2 as(
select [rn] = row_number() over(
order by [Id] -- also order by [LogDate], [LogTime]
), *
from #your_temp_table_name
where [InoutMode] = 0
)
select
t1.[LogTime] [InTime],
t2.[LogTime] [OutTime]
from cte t1
left join cte2 t2
on t1.[rn] = t2.[rn];
如果你想把结果集放到一个新的临时表中。那么最后一部分可以修改为
select
t1.[LogTime] [InTime],
t2.[LogTime] [OutTime]
into #your_new_temp_table_name
from cte t1
left join cte2 t2
on t1.[rn] = t2.[rn];
Find demo here
【解决方案3】:
使用INSERT INTO .. SELECT FROM 构造类似
insert into #temp2
select ID, LogDate,
case when InoutMode = 1 then LogTime end as InTime,
case when InoutMode = 0 then LogTime end as OutTime,
InoutMode
from #temp1