SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to create multiple rows from single row
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Niki
Yak Posting Veteran

51 Posts

Posted - 03/05/2013 :  18:57:14  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

4614 Posts

Posted - 03/05/2013 :  18:59:09  Show Profile  Reply with Quote
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 - 03/05/2013 :  19:04:00  Show Profile  Reply with Quote
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

Edited by - Niki on 03/05/2013 19:47:52
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52325 Posts

Posted - 03/06/2013 :  01:16:34  Show Profile  Reply with Quote

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


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

Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.09 seconds. Powered By: Snitz Forums 2000