Skip to content
Advertisement

How to print pattern output in Oracle’s SQL

I have a table with below data

Table : emp

name
A
B
C
D

Expected Output :

names
A
AB
ABC
ABCD

I only know how to print data in horizontal form

SELECT LISTAGG(name,'|') 
  FROM emp;

Not sure how to cut the horizontal and get expected output

Advertisement

Answer

You can use a hierarchical query:

SELECT REPLACE(SYS_CONNECT_BY_PATH(name, '|'), '|') AS names
FROM   ( SELECT ROW_NUMBER() OVER (ORDER BY name) AS rn,
                name
         FROM   emp )
START WITH rn = 1
CONNECT BY PRIOR rn + 1 = rn;

Which, for the sample data:

CREATE TABLE emp (name) AS
SELECT 'A' FROM DUAL UNION ALL
SELECT 'B' FROM DUAL UNION ALL
SELECT 'C' FROM DUAL UNION ALL
SELECT 'D' FROM DUAL;

Outputs:

NAMES
A
AB
ABC
ABCD

db<>fiddle here

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement