我有一个像下面这样的表,该表包含一条记录(可能是几条记录),但我需要每一条都会得到三条相似的记录,其中一列值不同。
例如,该表包含如下记录:
表名:时间戳
Id SalesMan_Id Module_Cdoe Time_In Time_Out
1 13524 Analysis 1.30pm 1.40pm
2 12543 Analysis 2.10pm 2.30pm
从上表中,我需要输出(结果集),如下所示:
Id SalesMan_Id Module_Cdoe Time_In Time_Out
1 13524 Analysis 1.30pm 1.40pm
2 13524 Photo 1.30pm 1.40pm
3 13524 Survey 1.30pm 1.40pm
4 13524 Merchand 1.30pm 1.40pm
5 12543 Analysis 2.10pm 2.30pm
6 12543 Photo 2.10pm 2.30pm
7 12543 Survey 2.10pm 2.30pm
8 12543 Merchand 2.10pm 2.30pm
实现我期望的SQL查询是什么?
假设该表包含如下内容:
Id SalesMan_Id Module_Cdoe Time_In Time_Out
1 13524 Analysis 1.30pm 1.40pm
2 13524 Photo 1.30pm 1.40pm
然后我还需要输出(结果集),如下所示:
Id SalesMan_Id Module_Cdoe Time_In Time_Out
1 13524 Analysis 1.30pm 1.40pm
2 13524 Photo 1.30pm 1.40pm
3 13524 Survey 1.30pm 1.40pm
4 13524 Merchand 1.30pm 1.40pm
答案 0 :(得分:3)
Declare @TimeStamp table (Id int, SalesMan_ID int, Module_Cdoe varchar(50),Time_In varchar(10),Time_Out varchar(10))
Insert into @TimeStamp values
(1,13524,'Analysis','1:30pm','1:40pm'),
(2,12543,'Analysis','2:10pm','2:30pm')
;with cteBase (Seq,Module_Cdoe) as(
Select 1,'Analysis' union all
Select 2,'Photo' union all
Select 3,'Survey' union all
Select 4,'Merchand'
)
Select id=Row_Number() over (Order By Time_In,SalesMan_id,Seq)
,SalesMan_id
,b.Module_Cdoe
,Time_In
,Time_Out
from @TimeStamp A
Join cteBase B on (A.Module_Cdoe='Analysis')
Order By 1
返回
id SalesMan_id Module_Cdoe Time_In Time_Out
1 13524 Analysis 1:30pm 1:40pm
2 13524 Photo 1:30pm 1:40pm
3 13524 Survey 1:30pm 1:40pm
4 13524 Merchand 1:30pm 1:40pm
5 12543 Analysis 2:10pm 2:30pm
6 12543 Photo 2:10pm 2:30pm
7 12543 Survey 2:10pm 2:30pm
8 12543 Merchand 2:10pm 2:30pm
答案 1 :(得分:2)
Demo Here 根据Arul评论更新
;with cte(mod_code,id)
as
(
select 'Analysis',1 union all
select 'photo',2 union all
select 'survey',3 union all
select 'merchand',4
)
select distinct salesman_id,c.*,
time_in,time_out
from #temp
cross join
cte c