【问题标题】:Looping through a table to create a temp table循环遍历表以创建临时表
【发布时间】:2016-07-11 18:16:55
【问题描述】:

我有一张表,其中有一个日期字段是周数,然后是 7 个十进制字段表示工作时间。

我想遍历这个表,并在一个临时表中为一周中的每一天创建一行,其中包含每天的工作时间。

我可以做一个简单的...

SELECT  UserID, WeekNum, Hours1, Hours2, Hours3, Hours4, Hours5, Hours6, Hours7
INTO    #NCExtract
FROM    Timesheet

但我需要有结果

UserID Date Hours
UserID Date Hours
UserID Date Hours
UserID Date Hours
UserID Date Hours
UserID Date Hours
UserID Date Hours

从一排开始。于是我开始了以下方式:

create table #NCExtract
(
    UserID int, 
    WorkDate DateTime, 
    WorkHours decimal
) 

Select *
From   TimeSheetTable

While (Select Count(*) From TimeSheetTable) > 0
Begin
    Create #NCExtract record with 1st date hours
    Create #NCExtract record with 2nd date hours
    Create #NCExtract record with 3rd date hours
    Create #NCExtract record with 4th date hours
    Create #NCExtract record with 5th date hours
    Create #NCExtract record with 6th date hours
    Create #NCExtract record with 7th date hours
End

我不确定如何在循环中提供信息来创建记录。

【问题讨论】:

    标签: sql-server tsql temp


    【解决方案1】:

    我可以想出两种方法来做你想做的事(假设是 t-sql,但也应该适用于其他数据库)。

    unpivot :https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

    或 7 个选择语句(粗略估计见下文)

    --Since i do not have a table definition of timesheet table might be a little off
    create table #NCExtract ( UserID int, WorkDate DateTime, WorkHours decimal )
    
    insert into #NCExtract (UserID, WorkDate, WorkHours)
    Select Userid, DateAdd(d,1,WeekNum), Hours1 -- I assumed that the weeknum column was a date/datetime
    From TimeSheetTable 
    Where Hours1 is not null -- add any needed logic (e.g. not null or <> 0)
    
    insert into #NCExtract (UserID, WorkDate, WorkHours)
    Select Userid, DateAdd(d,2,WeekNum), Hours2 --update the date add for each select
    From TimeSheetTable
    Where Hours2 is not null
    
    --3, 4, 5, 6 ommited
    
    select * from #NCExtract 
    order by UserID, WorkDate -- if the final result needs to be sorted, sort when selecting
    

    【讨论】:

    • 这有点不对劲,但我想我明白你在说什么。我将不得不运行 7 次插入,基本上每天一个。我能做到。谢谢!
    • @Dlangschied 很高兴我能帮上忙!我知道这会有点偏离,但想通过所提供的信息为您提供一个快速的近似值,以便为您指明正确的方向。
    • @Dlangschied 如果我的回答为您提供了您需要的信息,您能否将其标记为已接受的答案,如果没有,您还坚持什么?
    猜你喜欢
    • 1970-01-01
    • 2019-06-12
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多