SQL

All posts relating to Oracle PL/SQL development.

Moderator: Tim...

SQL

Postby chatwidravi » Thu Aug 22, 2013 3:18 pm

i have a table called t1 like
id img
1 x
2 y
3 z
and i want the output like

id img
1 x
2 x,y
3 x,y,z
how can we do that in oracle
chatwidravi
Member
 
Posts: 5
Joined: Thu Aug 08, 2013 8:28 am

Re: SQL

Postby Tim... » Thu Aug 22, 2013 5:26 pm

Hi.

Once again Analytic Functions save the day.

http://www.oracle-base.com/articles/mis ... ctions.php

More specifically LISTAGG.

http://www.oracle-base.com/articles/mis ... hp#listagg

Your starting point is this.

Code: Select all
CREATE TABLE t1 (
  id  NUMBER,
  img VARCHAR(10)
);

INSERT INTO t1 VALUES (1, 'x');
INSERT INTO t1 VALUES (2, 'y');
INSERT INTO t1 VALUES (3, 'z');
COMMIT;


So your query is this.

Code: Select all
COLUMN img FORMAT A20

SELECT a.id,
       (SELECT LISTAGG(b.img, ',') WITHIN GROUP (ORDER BY id)
        FROM   t1 b
        WHERE  b.id <= a.id) AS img
FROM   t1 a
ORDER BY a.id;

        ID IMG
---------- --------------------
         1 x
         2 x,y
         3 x,y,z

3 rows selected.

SQL>


The COLUMN definition is just to make it neater in SQL*Plus.

Cheers

Tim...
Tim...
Oracle ACE Director
Oracle ACE of the Year 2006 - Oracle Magazine Editors Choice Awards
OakTable Member
OCP DBA 7.3, 8, 8i, 9i, 10g, 11g
OCP Advanced PL/SQL Developer
Oracle Database: SQL Certified Expert
My website: http://www.oracle-base.com
My blog: http://www.oracle-base.com/blog
Tim...
Site Admin
 
Posts: 17937
Joined: Mon Nov 01, 2004 5:56 pm
Location: England, UK


Return to Oracle SQL and PL/SQL Development

Who is online

Users browsing this forum: No registered users and 4 guests

cron