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.
Author |
Topic |
Kalaiselvan
Posting Yak Master
112 Posts |
Posted - 2012-03-15 : 21:02:05
|
Hi, Need a query to look after the child tables data and have to group the columns for total days in behalf of date.TableA:[ID] [StatusID] [Date] [PrevStatusID] 1 101 01-02-2012 0 1 102 15-02-2012 101 1 103 29-02-2012 102 1 105 15-03-2012 103 2 101 01-03-2012 0 3 101 01-03-2012 0 3 110 15-03-2012 101From the above table need the output for Status wise Group. Where as Last status ID output will be from getdate() function.Consider Getdate=16-03-2012. Then my result will be[101] [102] [103] [105] [110] 43 14 15 1 1For StatusID=1 and ID=1 Date=01-02-2012 and nextstatusID=102 and its date= 15-02-2012 Hence Total days=14And StatusID=101 and ID=2 Date=01-03-2012 and no Next statusID, Hence consider GETDATE. Henve Total days=15For StatusID=1 and ID=3 Date=01-03-20122 and nextstatusID=110 and its date= 15-03-2012 Hence Total days=14So the result set as StatusID=101 is 14+15+14=43.Please provide me the query to get this result.Regards,Kalai |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-03-15 : 23:01:07
|
[code]set dateformat dmydeclare @test table([ID] int,[StatusID] int, [Date] datetime,[PrevStatusID] int)insert @testselect 1, 101, '01-02-2012', 0 union allselect 1, 102, '15-02-2012', 101 union allselect 1, 103, '29-02-2012', 102 union allselect 1, 105, '15-03-2012', 103 union allselect 2, 101, '01-03-2012', 0 union allselect 3, 101, '01-03-2012', 0 union allselect 3, 110, '15-03-2012', 101select *from(select t1.StatusID,datediff(dd,t1.date,coalesce(t2.date,getdate())) as dayselapsedfrom @test t1left join @test t2on t2.[PrevStatusID] = t1.StatusIDand t1.id = t2.id)tpivot (sum(dayselapsed) for StatusID IN ([101],[102],[103],[105]))p101 102 103 105-----------------------------43 14 15 1[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|
|