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 (<br /> Text VARCHAR2(10) ,<br /> min NUMBER ,<br /> max NUMBER) ; <br /> <br /> INSERT INTO tmp VALUES ('AAA', 2,4) ;<br /> INSERT INTO tmp VALUES ('BBB', 25,28) ;<br /> 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 tmp.text || ' Value is ' || b.L FROM tmp,<br /> (SELECT LEVEL L FROM dual<br /> CONNECT BY level <= (SELECT max (max) FROM tmp )<br /> ) b<br /> WHERE b.L >= min<br /> AND b.L <= max<br /> ORDER BY 1
In 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 cnt AS (<br /> SELECT LEVEL L FROM dual<br /> CONNECT BY level <= (SELECT max (max) FROM tmp)<br /> )<br /> SELECT tmp.text || ' Value is ' || cnt.L<br /> FROM tmp , cnt<br /> WHERE tmp.min <= cnt.L<br /> AND tmp.max >= cnt.L<br /> ORDER BY 1
SELECT text || ' Value is ' || L<br /> FROM (<br /> SELECT distinct tmp.text, level L, tmp.min<br /> from tmp<br /> connect by level <= tmp.max<br /> )<br /> WHERE L >= min<br /> order by text , L
Friends, please share your knowledge as well, if you know any other method.
Follow me at : Facebook