2016-07-11 4 views
0

나는 주 숫자 인 하나의 날짜 필드와 근무 시간을 나타내는 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 

루프를 작성하여 레코드를 만드는 방법을 모르겠습니다.

답변

0

나는 당신이 원하는 것을 할 수있는 두 가지 방법을 생각할 수있다. (t-sql을 가정하지만 다른 db도 사용할 수 있어야한다.)

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

7 SELECT 문이 조금 꺼져,하지만 난 당신이 무슨 말의 요점을 얻을 생각

--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 
+0

(대략적인 내용은 아래 참조). 본질적으로 매일 7 개의 인서트를 실행해야합니다. 나는 그걸 할 수있어. 감사! – Dlangschied

+0

@Dlangschied 기꺼이 도와 드릴 수 있습니다! 나는 그것이 조금 벗어날 것임을 알았지 만 제공된 정보에서 당신에게 올바른 방향으로 당신을 안내하는 빠른 근사치를주고 싶었습니다. –

+0

@Dlangschied 내 대답이 당신에게 필요한 정보를 주었다면 당신은 그것을 수용 대답으로 표시 할 수 있습니까? –

관련 문제