Question

I am working with MSSQL 2012 and am trying to figure out how to take a set with parent values in one column and child values in another column, and combine that into one column with the parent only shown in a single row and each respective child shown beneath it. Exercises with row_number()/partition have not been fruitful.

How can I make this happen?

Thanks.

set nocount on
declare @parchi table ( parenttext varchar(20) , childtext varchar(20) )
insert into @parchi values ( 'parenta' , 'childa' )
insert into @parchi values ( 'parenta' , 'childc' )
insert into @parchi values ( 'parenta' , 'childb' )
insert into @parchi values ( 'parentb' , 'child1' )
insert into @parchi values ( 'parentb' , 'child3' )
insert into @parchi values ( 'parentb' , 'child2' )


select childtext,ROW_NUMBER() over (partition by parenttext order by parenttext,childtext) as tempordnum from @parchi 


-- below is shape of the result set. what i came up with does not include the parent at the top of each grouping set (pun intentional(.
parenta
childa
childb
childc
parentb
child1
child2
child3
Était-ce utile?

La solution

You can do it this way. It first gets parents and assigns a rank to each one of them. Then it gets children and assigns parent rank again plus a child rank. At the end it gets the result from the union sorted by parent order and then child order.

You can add additional columns in ORDER BY part of DENSE_RANK() to further sort children.

;with cte as
(
    select distinct parenttext, DENSE_RANK() OVER (ORDER BY parenttext) parentorder, 0 childorder 
    from @parchi

    union all

    select childtext, DENSE_RANK() OVER (ORDER BY parenttext), DENSE_RANK() OVER (ORDER BY childtext)
    from @parchi
)

select parenttext from cte
order by parentorder, childorder

Autres conseils

try this suggestion:

you will need to select the parent, and the child separately and then u will UNION the both select.

  1. select the parent, and use row_number to create the parent id (parenta id = 1, parent b id = 2)

  2. select the child, and use dense_rank based on the parenttext field. this will give the child an id (childa - childc will have id = 1, child1-3 will have id = 2)

  3. union the result and you will get what u want

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top