Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

appending row number in sql select statement with row value

I am trying to concatenate the select statment results in one row.
For eg : For this select statement output :

Name  
ABC  
DEF  
GHI

I needed following Output :
Name

1 ABC, 2 DEF, 3 GHI  

(Means row number should be appended in front for each row)
I am using wm_concat() function but it is giving me the following o/p : ABC,DEF,GHI
Can anyone help ?

like image 357
Harpreet Avatar asked Dec 05 '25 12:12

Harpreet


1 Answers

It sounds like you want something similar to this. The listagg() function is available in Oracle 11g+:

select listagg(cast(rownum as varchar2(20))||' '|| name, ', ') 
        within group (order by name) name
from yourtable

See SQL Fiddle with Demo

Results:

|                NAME |
-----------------------
| 1 ABC, 2 DEF, 3 GHI |

If you do not have Oracle 11g, then you can use wm_concat():

select wm_concat(cast(rownum as varchar2(20))||' '|| name) name
from yourtable
like image 151
Taryn Avatar answered Dec 08 '25 03:12

Taryn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!