http://www.sqler.com/571713 질문에서 문제가 있어서 추가 질문합니다.
아래 붉은색 한줄을 추가를 하니,
12:00 에 로우가 추가로 생겨버렸습니다.
같은 시간대에는 한 로우가 되어야 합니다.
어떻게 해야 할까요. 도와주세요.
-------------------- 결과 --------------------------
s_time e_time 201 202 501
10:00 10:30 2013-2371B001 NULL NULL
10:30 11:00 2013-2371B001 NULL NULL
11:00 11:30 NULL NULL 2013-2371B001
11:30 12:00 NULL NULL 2013-2371B001
12:00 12:30 2013-2371C004 NULL NULL
12:30 13:00 2013-2371C004 NULL NULL
12:00 12:30 NULL 2013-2371A005 NULL
12:30 13:00 NULL 2013-2371A005 NULL
-------- 도와주신 쿼리 --------------------------
WITH
DT1 as
( select '09:00' s_time , '11:00' e_time ,'2013-2371B001' code ,'201' rmode union all
select '11:00' ,'12:00' ,'2013-2371B001' ,'501' union all
select '12:00' ,'16:00' ,'2013-2371C004' ,'201' union all
select '12:00' ,'16:00' ,'2013-2371A005' ,'202'
)
select * into #DT1 from DT1;
WITH
DT2 as
(
select '10:00' s_time , '10:30' e_time union all
select '10:30' s_time , '11:00' e_time union all
select '11:00' s_time , '11:30' e_time union all
select '11:30' s_time , '12:00' e_time union all
select '12:00' s_time , '12:30' e_time union all
select '12:30' s_time , '13:00' e_time )
select * into #DT2 from DT2;
declare @sql varchar(max)
set @sql = 'SELECT B.s_time ,B.e_time ' + CHAR(10) ;
select @sql = @sql + ' , case when A.rmode = ''' +rmode +''' then A.code end ['+rmode+']' + CHAR(10)
from #DT1 group by rmode
set @sql = @sql + ' FROM #DT2 B JOIN #DT1 A ON A.s_time <= B.s_time AND A.E_time >= B.e_time '
print @sql
exec(@sql)
declare @sql varchar(max)
set @sql = 'SELECT B.s_time ,B.e_time ' + CHAR(10) ;
select @sql = @sql + ' , max(case when A.rmode = ''' +rmode +''' then A.code end) ['+rmode+']' + CHAR(10)
from #DT1 group by rmode
set @sql = @sql + ' FROM #DT2 B JOIN #DT1 A ON A.s_time <= B.s_time AND A.E_time >= B.e_time '
set @sql = @sql + ' GROUP BY B.s_time ,B.e_time ' + CHAR(10)
set @sql = @sql + ' ORDER BY B.s_time ,B.e_time ' + CHAR(10)
print @sql
exec(@sql)