如何将行从一个临时 table 插入到另一个临时 sql

How to insert rows from one temp table to another in sql

    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   

以上结果来自临时 table.now 我想将 LogTime 插入另一个临时 table 如下所示。

      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

使用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

要将一个 table 的行插入到另一个 table 中,您可以编写此 SQL 查询:

INSERT INTO anotherTemp (InTime)
    SELECT LogTime
    FROM Temp
    WHERE InoutMode = 1  

INSERT INTO anotherTemp (OutTime)
    SELECT LogTime
    FROM Temp
    WHERE InoutMode = 0 

查看此link了解更多http://www.dofactory.com/sql/insert-into

使用 2 个 cte,一个用于 InoutMode1,另一个用于 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];

如果你想把结果集放到一个新的临时文件中table。然后最后一部分可以修改为

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