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
 grouping by parent ID

Author  Topic 

nbalraj
Starting Member

21 Posts

Posted - 2011-03-18 : 17:41:05
Hello,

I have this table with the below record set

PrimaryID ParentID PrimaryName PrimaryAmount
1 0 One 100
2 1 Two 200
3 0 Three 300
4 1 Four 400
5 3 Five 500

I want the result as
PrimaryID ParentID PrimaryName PrimaryAmount
1 0 One 100
2 1 Two 200
4 1 Four 400
3 0 Three 300
5 3 Five 500

can anyone help me with some directions. as you can see first record should be the primaryid record followed with the records that has that primary id as parentid.

thanks,


pduffin
Yak Posting Veteran

68 Posts

Posted - 2011-03-18 : 20:09:40
create table #tmppmd (pid int,parid int)
insert into #tmppmd values (1,0 )
insert into #tmppmd values (2,1 )
insert into #tmppmd values (3,0 )
insert into #tmppmd values (4,1 )
insert into #tmppmd values (5,3 )

select *
from
(
select pmd1.pid as id,pmd1.*
from #tmppmd pmd1
where parid = 0
union all
select pmd2.parid as id,pmd2.*
from #tmppmd pmd1
join #tmppmd pmd2 on pmd2.parid = pmd1.pid
) a
order by a.id,a.pid
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2011-03-18 : 23:53:23
will you have more than 2 level ?


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

nbalraj
Starting Member

21 Posts

Posted - 2011-03-20 : 01:02:33
Nope, there will be only 1 level
Go to Top of Page

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2011-03-20 : 08:07:17
If there will be only two levels (which would mean that the first level should always be zero to avoid accidental level growth), you could sort like this:
	case when parentId = 0 then cast(id as varchar(32))
else cast (parentId as varchar(32)) + right('00000'+cast(id as varchar(32)),5) end,
id
But, this is not the most ideal if you want to have any hope of extensibility. If you do, I would think in terms of a recursive query to figure out the ordering. Not clear in my mind how to do it, but I am sure many others here can do it with half their brain tied behind their back.
Go to Top of Page

nbalraj
Starting Member

21 Posts

Posted - 2011-03-22 : 12:46:57
pduffin's idea helped me. Thanks for all your inputs.
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2011-03-22 : 13:00:20
quote:
Originally posted by nbalraj

Nope, there will be only 1 level



Added to the biggest lies in the database b'dness list

Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx


Want to help yourself?

http://msdn.microsoft.com/en-us/library/ms130214.aspx

http://weblogs.sqlteam.com/brettk/

http://brettkaiser.blogspot.com/


Go to Top of Page
   

- Advertisement -