SQL Puzzle | The Hierarchy Spacing Puzzle – A SINGLE SELECT

In this puzzle you have to create two new columns from the existing columns. In the first column you have to remove the parents path from the child and prefix space to the child just to differentiate.
In the second column you just have to prefix space to the child just to differentiate. Please check out the sample input and the expected output. Can you do that in a SINGLE SELECT

Sample Input

Id Vals
1 \Pawan
2 \Pawan\Kumar
3 \Pawan\Kumar\Khowal
4 \Pawan\Kumar\Khowal\SQL
5 \Pawan\Khowal
6 \Sharlee
7 \Sharlee\Diwan

Expected Output

Script – DDL and INSERT Sample Data

 ```-- CREATE TABLE Prima ( Id INT ,Gr VARCHAR(10) ,Val INT ) GO INSERT INTO Prima VALUES (1,'a',10), (2,'b',15), (3,'c',45) CREATE TABLE Limits ( Gr VARCHAR(10) ,StartLimit INT ,EndLimit INT ) GO INSERT INTO Limits VALUES ('a',0,9), ('a',20,100), ('b',10,14), ('b',20,100), ('c',10,50) GO -- ```

SOLUTION 1

 ```-- SELECT h.* , CONCAT ( SPACE(10 * ( LEN((LEFT(Vals, LEN(Vals) - u))) - LEN(REPLACE((LEFT(Vals, LEN(Vals) - u)),'\','')))) ,' ' ,RIGHT(Vals, u) ) Treestructure1 ,CONCAT ( SPACE(10 * ( LEN((LEFT(Vals, LEN(Vals) - u))) - LEN(REPLACE((LEFT(Vals, LEN(Vals) - u)),'\','')))) , ' ' , Vals ) Treestructure2 FROM Hierarchies h CROSS APPLY (VALUES(CHARINDEX('\',REVERSE(Vals)))) t(u) -- ```

OUTPUT – 1

Enjoy 🙂

Pawan Khowal

Pawan is a SQL Server Developer. If you need any help in writing code/puzzle or training please email at – pawankkmr”AT”gmail.com. Meanwhile please go throgh the top pages from his blog.

Page Detail URL
☛ SQL Tricky Queries https://msbiskills.com/sql-puzzles-finding-outputs/
☛ SQL Server Performance tuning Articles https://msbiskills.com/sql-performance-tuning/
☛ SQL Server Articles https://msbiskills.com/t-sql/
☛ SQL Interview Questions & Answers https://msbiskills.com/sql-server-interview-questions/