SQL

Display Same Record Multiple time from SQL Query

Sending
User Rating 5 (2 votes)

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.

First check the sample data and desired output.

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  tmp.text || '   Value   is   ' || b.L  FROM tmp,
       (SELECT  LEVEL L FROM dual
        CONNECT BY level <= (SELECT  max (max) FROM tmp )
        ) b
WHERE   b.L >= min
AND     b.L <= max
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 (
        SELECT  LEVEL L FROM    dual
        CONNECT BY level <=  (SELECT  max (max) FROM tmp)
    )
SELECT  tmp.text || '   Value   is   ' || cnt.L
FROM    tmp , cnt
WHERE   tmp.min <= cnt.L
AND     tmp.max >= cnt.L
ORDER BY 1

Method 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 , L​

Friends, please share your knowledge as well, if you know any other method.

Follow me at : Facebook

Share your Thoughts