Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

CTE with pivotting

$
0
0

Our db in SQL Server has a ragged heirarchy with 6 columns,

i have created some insert code to get it perfect.

Desired output is to find the top layer for each CostCentreid and not output any layers

where the isservice and issector are both SET to 0, but still consider them part of the ladder

So if a 0,0 appears for these items i still want it to continue climbing the heirarchy to find the highest non 0,0 in that ladder.

here is a test sql script:

CREATE table #test

( ParentID int, CostCentre varchar(max), CostCentreID int, CostCentreCode varchar(max), ISService bit, ISSector bit ) GO INSERT into #test VALUES(10289,'Legal',88,'0107',0,0) INSERT into #test VALUES(10291,'ML Corp',10289,'MLCorpServ',0,1) INSERT into #test VALUES(10292,'IgnoreMe',10291,'MLCorpServ',0,0) INSERT into #test VALUES(10000,'Corp Services',10292,'CorpSvcs',1,0) INSERT into #test VALUES(10000,'Corp Services Top',10000,'CorpSvcstop',0,0)

And the query:

WITH r AS ( SELECT CAST(CostCentreid AS VARCHAR(max)) + ',' + CAST(parentid AS VARCHAR(max)) sb FROM #test UNION ALL SELECT sb +',' + CAST(parentid AS VARCHAR(max)) FROM r JOIN #test t ON rtrim(CAST(t.costcentreid AS VARCHAR(max)))=rtrim(right(r.sb,CHARINDEX(',',reverse(r.sb))-1)) WHERE t.parentid<>t.costcentreid ) SELECT * FROM r OPTION (MAXRECURSION 0)



Which outputs:

88,10289
88,10289,10291
88,10289,10291,10292
88,10289,10291,10292,10000

But my desired output is only ONE ROW -

88,10289,10292 because 10291 and 10000 are both not a sector OR a Sector (0,0) but it needs to ignore 10291 even though its a 0,0 as there is a higher level with a sector

Also i cant figure out how to add additional columns from the table, i want to display the CostCentreName in the next column

Can someone help me out with this ? thanks :) J




Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>