I would like to share a interview question where you have to display the same records multiple times using SQL query. This is very easy job with the help of PL/SQL block but here we will see, how we can do this using SQL query.
CREATE TABLE TMP ( Text VARCHAR2(10) , min NUMBER , max NUMBER) ; INSERT INTO tmp VALUES ('AAA', 2,4) ; INSERT INTO tmp VALUES ('BBB', 25,28) ; INSERT INTO tmp VALUES ('CCC', 10,13) ;Now come to solution , if somehow we get the series of number (like 1,2,3,4… Max) as a data set and then we can join this with original table to get desired output.
We can get this data set of number(like 1,2,3…) with the help of “Connect by Level” .
Here LEVEL is a pseudo column which returns 1 for a root row, 2 for a child of a root, and so on. CONNECT BY specifies the relationship between parent rows and child rows of the hierarchy. We use all these in hierarchical query. Will explain hierarchical query in detail in different article but not here.
First check below example to print number 1 to 10 with help of CONNECT BY LEVEL. This is the common question which is asked during interview to print number 1 to 10 from dual.SELECT LEVEL FROM dual CONNECT BY LEVEL <= 10 ;Above query return number 1 to 10.
We will use this method to solve given problem.
Method 1 :
SELECT&nbsp; tmp.text || '&nbsp;&nbsp; Value&nbsp;&nbsp; is&nbsp;&nbsp; ' || b.L&nbsp; FROM tmp, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (SELECT&nbsp; LEVEL L FROM dual &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; CONNECT BY level &lt;= (SELECT&nbsp; max (max) FROM tmp ) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ) b WHERE&nbsp;&nbsp; b.L &gt;= min AND&nbsp;&nbsp;&nbsp;&nbsp; b.L &lt;= max ORDER BY 1In above query, line no 2, 3 will gives number series 1 to 28. and I am joining this with original table.
Method 2: This is same query as above ,just I am writing in different way.
WITH&nbsp;&nbsp;cnt AS ( &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;SELECT&nbsp; LEVEL L FROM&nbsp;&nbsp;&nbsp; dual &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; CONNECT BY level &lt;=&nbsp; (SELECT&nbsp; max (max) FROM tmp) &nbsp; &nbsp; ) SELECT&nbsp; tmp.text || '&nbsp;&nbsp; Value&nbsp;&nbsp; is&nbsp;&nbsp; ' || cnt.L FROM&nbsp;&nbsp;&nbsp; tmp , cnt WHERE&nbsp;&nbsp; tmp.min &lt;= cnt.L AND&nbsp;&nbsp;&nbsp;&nbsp; tmp.max &gt;= cnt.L ORDER BY 1Method 3:
SELECT text || ' Value is ' || L FROM ( SELECT distinct tmp.text, level L, tmp.min from tmp connect by level <= tmp.max ) WHERE L >= min order by text , LFriends, please share your knowledge as well, if you know any other method.
Follow me at : Facebook