Tuesday, June 9, 2015

Scenario based SQL Interview Question

I have come across the below scenario in one of the forums and I'm giving the solution here. 

SRC:
Have source data like below


Output should like below:





what is the SQL to get output as shown above?

Ans: This can be achieved using loops in SQL and below is the query: 

WITH t AS (SELECT col1, col2 v FROM src)
  SELECT CEIL (v) - i AS seq, col1,
         CASE WHEN (i = 0 AND CEIL (v) <> v) 
              THEN 1 + v - (CEIL (v) - i)
              ELSE 1
         END  AS COL2
  FROM t, 
    XMLTABLE ('for $i in 0 to xs:int(D) return $i'
    PASSING XMLELEMENT (d, CEIL (v) - 1) COLUMNS i INTEGER PATH '.')
ORDER BY col1, CEIL (v) - i 



Please refer the below link to know more about loops: 
http://www.dba-oracle.com/t_loop_sql.htm



5 comments:

  1. Thanks for giving Good Example.Fantastic article, Viral. Very well written, clear and concise. One of the best links explaining one to many and hierarchy in Sap security. Thanks a lot.It is uaefull to me and my training online training center

    ReplyDelete

  2. thank you for your wonderful information on informatica keep sharing thank you
    visit our site to learn
    learn Advanced informatica!

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. I feel Informatica is the best and the most useful tool about vivid usages and its aspects.

    Informatica Read Soap API

    ReplyDelete