Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to create multiple rows from single row

Author  Topic 

Niki
Yak Posting Veteran

51 Posts

Posted - 2013-03-05 : 18:57:14
I have table A with StuID and table B with Stuid & multiple Enter & leavedates. I want to create multiple rows for each enter and leavedate.

Table A
StuID 99999

Table B
Stuid 99999 edate ldate edate1 ldate1 edate2 ldate2

Result should look like

99999 edate ldate
99999 edate1 ldate1
99999 edate2 ldate2

How can I do that? I tried CROSS APPLY but I don't think I am using it correctly. Please help.



Niki

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2013-03-05 : 18:59:09
Is each of those dates a column in the table or are they a single concatenated string column?

http://www.sqlservercentral.com/articles/Best+Practices/61537/
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx
Go to Top of Page

Niki
Yak Posting Veteran

51 Posts

Posted - 2013-03-05 : 19:04:00
They are Datetime type. This is how I am doing it and I know there must be a better way to do ot. Please help
select a.studentno, b.schno , edate as Enterdate, ldate as LeaveDate
fromtblA a
inner join tblB b on a.studentno = b.Studentno

union all
select a.studentno, schno2 , edate2 as Enterdate, ldate2 as LeaveDate
fromtblA a
inner join tblB b on a.studentno = b.Studentno

union all
select a.studentno, schno3 , edate3 as Enterdate, ldate3 as LeaveDate
fromtblA a
inner join tblB b on a.studentno = b.Studentno
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-03-06 : 01:16:34
[code]
select p.studid,p.val as edateval, q.val as ldateval
from
(
select studid,dates,val,row_number() over (partition by studid order by dates) as seq
from (select studid,edate,edate1,edate2 from table )t
unpivot (val for dates in (edate,edate1,edate2))u
)p
inner join
(
select studid,dates,val,row_number() over (partition by studid order by dates) as seq
from (select studid,ldate,ldate1,ldate2 from table )m
unpivot (val for dates in (ldate,ldate1,ldate2))n
)q
on q.studid=p.studid
and q.seq=p.seq
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -