Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

Flatten hierarchy Expand / Collapse
Author
Message
Posted Tuesday, December 31, 2013 3:54 AM
Old Hand

Old HandOld HandOld HandOld HandOld HandOld HandOld HandOld Hand

Group: General Forum Members
Last Login: 2 days ago @ 7:54 AM
Points: 319, Visits: 782
I know there have been several forum discussions about flattening hierarchies using recursive CTEs but the examples I have found have a ParentID field in the data. My data does not have this.

Please take a look at this sample code

declare @table table
(id varchar(10),
levelid int,
leveldesc varchar(250))

insert into @table
select 'DP961A1111', 1, 'LevelDesc1'
union
select 'DP961A1111', 2, 'LevelDesc2'
union
select 'DP961A1111', 3, 'LevelDesc3'

select * from @table

--I need to display the results like this:
select 'DP961A1111' as id, 'LevelDesc1' as LevelDesc1, 'LevelDesc2' as LevelDesc2, 'LevelDesc3' as LevelDesc3

Can you guys help?
Post #1526715
Posted Tuesday, December 31, 2013 5:11 AM


SSCertifiable

SSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiable

Group: General Forum Members
Last Login: Today @ 9:41 AM
Points: 6,748, Visits: 12,843
Try this - it's called a CROSSTAB query:

SELECT id,
LevelDesc1 = MAX(CASE WHEN levelid = 1 THEN leveldesc ELSE NULL END),
LevelDesc2 = MAX(CASE WHEN levelid = 2 THEN leveldesc ELSE NULL END),
LevelDesc3 = MAX(CASE WHEN levelid = 3 THEN leveldesc ELSE NULL END)
FROM @table
GROUP BY id

Here's a great article to explain how it works, and how far you can go with it:
http://www.sqlservercentral.com/articles/T-SQL/63681/


“Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
Exploring Recursive CTEs by Example Dwain Camps
Post #1526725
Posted Tuesday, December 31, 2013 8:29 AM
Old Hand

Old HandOld HandOld HandOld HandOld HandOld HandOld HandOld Hand

Group: General Forum Members
Last Login: 2 days ago @ 7:54 AM
Points: 319, Visits: 782
I have came across the crosstab query before but only in theory, never used it in anger! I'll give this a go.

Thanks for your help, greatly appreciated.
Post #1526762
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse