String to rows
I know this has been asked many times, and I got the simple solution for converting a (comma separated) string to rows like this:
with t as (select 'aa;bb;cc;dd;ee;ff' as txt from dual)
select regexp_substr (txt, '[^;]+', 1, level)
from t
connect by level <= length(regexp_replace(txt,'[^;]*'))+1;This works fine for one string. But my situation is that I have a table like this:
col1 col2
A aa;bb;cc
B dd
etc.I want to convert this to:
A aa
A bb
A cc
B dd
etc.I can do this with a pipelined function or I can do this with a group by or unique in my sql, e.g.:
with t as (select 'A' as what, 'aa;bb;cc' as txt from dual
union
select 'B' as what, 'dd' as txt from dual)
select unique what,REGEXP_SUBSTR (txt, '[^;]+', 1, level)
from t
connect by level <= length(regexp_replace(txt,'[^;]*'))+1;
W REGEXP_S
A bb
A aa
B dd
A cc
4 rows selected.In this example, with only two records A and B, this is no problem. But in the actual table I am using in my WITH clause, this select is performing slowly due to the UNIQUE.
with t as
(select col1, col2
from mytable
select unique col1, regexp_substr (col2, '[^,]+', 1, level)
from t
connect by level <= length(regexp_replace(col2,'[^,]*'))+1;Anybody with a suggestion how to improve this statement?
Hi,
It's very confusing to use "CONNECT BY LEVEL <= x" when there's more than one row.
Generate the highest level you'll ever need in a sub-query (called a counter table ) that is based on a one-row table.
Then join to the counter table in your main query.
For example:
WITH cntr AS
SELECT LEVEL AS n
FROM dual
CONNECT BY LEVEL <= 1 + ( SELECT MAX ( LENGTH ( REGEXP_REPLACE ( col2
, '[^;]'
FROM t
SELECT t.col1
, REGEXP_SUBSTR ( t.col2
, '[^;]+' -- Use + here, not *
, 1
, cntr.n
) AS col2_substr
FROM t
JOIN cntr ON cntr.n <= LENGTH ( REGEXP_REPLACE (col2 || ';', '[^;]'))
ORDER BY t.col1
, cntr.n
;Edited by: Frank Kulash on Oct 23, 2009 12:01 PM
Similar Messages
-
String to Row: Delimiter as part of the value
My DB Version - 10.2.0.4.0
I have a string like this
with t
as
select q'['My column',LPAD(TRIM(my_column),4,'0'),10,10000]' str
from dual
select * from tI am looking for a SQL solution that will convert this string into row like this
'My column'
LPAD(TRIM(my_column),4,'0')
10
10000Normal way to convert delimited string to row would be like this
with t
as
select q'['My column',LPAD(TRIM(my_column),4,'0'),10,10000]' str
from dual
select regexp_substr(str,'[^,]+',1,level) val
from t
connect by level <= length(str)-length(replace(str,','))+1But this would result in
'My column'
LPAD(TRIM(my_column)
4
'0')
10
10000 But this is incorrect. So any idea how to solve it?Karthick_Arp wrote:
I totally understand. But we should also accept the fact that at times we get such crazy stuff to work with.
Just hoping that some one comes up with a super cool sql to do this ;)Something like this perhaps?
SQL> ed
Wrote file afiedt.buf
1 with t as (select q'['My column',LPAD(TRIM(my_column),4,'0'),10,10000]' str from dual)
2 ,x as (select regexp_substr(str, '[^(]+', 1, rownum) str, rownum as lvl
3 from t
4 connect by rownum <= length(regexp_replace(str, '[^(]'))+1
5 )
6 ,y as (select x.str as orig_str, lvl
7 ,replace(regexp_replace(x.str, '[^\)]+$'),',','~')||regexp_substr(x.str, '[^\)]+$') as str2
8 from x
9 )
10 ,z as (select ltrim(sys_connect_by_path(str2, '('),'(') as str
11 from y
12 where connect_by_isleaf = 1
13 connect by lvl = prior lvl + 1
14 start with lvl = 1
15 )
16 --
17 select rownum rn, replace(regexp_substr(str, '[^,]+', 1, rownum),'~',',') str
18 from z
19* connect by rownum <= length(regexp_replace(str, '[^,]'))+1
SQL> /
RN STR
1 'My column'
2 LPAD(TRIM(my_column),4,'0')
3 10
4 10000
SQL> ed
Wrote file afiedt.buf
1 with t as (select q'['My column',LPAD(TRIM(SUBSTR(my_column,4)),4,'0'),10,SUBSTR('FRED',4),10000]' str from dual)
2 ,x as (select regexp_substr(str, '[^(]+', 1, rownum) str, rownum as lvl
3 from t
4 connect by rownum <= length(regexp_replace(str, '[^(]'))+1
5 )
6 ,y as (select x.str as orig_str, lvl
7 ,replace(regexp_replace(x.str, '[^\)]+$'),',','~')||regexp_substr(x.str, '[^\)]+$') as str2
8 from x
9 )
10 ,z as (select ltrim(sys_connect_by_path(str2, '('),'(') as str
11 from y
12 where connect_by_isleaf = 1
13 connect by lvl = prior lvl + 1
14 start with lvl = 1
15 )
16 --
17 select rownum rn, replace(regexp_substr(str, '[^,]+', 1, rownum),'~',',') str
18 from z
19* connect by rownum <= length(regexp_replace(str, '[^,]'))+1
SQL> /
RN STR
1 'My column'
2 LPAD(TRIM(SUBSTR(my_column,4)),4,'0')
3 10
4 SUBSTR('FRED',4)
5 10000
SQL>Seems to work, but don't hold me to that. :D -
Converting comma separated string into rows
for my procedure varchar2 is i/p paramter. i will get this i/p from java. this string value is like 'VTP,VR','VM'.
i want to split taht string into rows ie o/p will be
VTR
VR
VM.
how to do this.Hi,
As always, the solution depends on your data, your requirements, and you Oracle version.
Here's one way:
-- Simulating Java input with a bind variable:
VARIABLE str VARCHAR2 (100)
EXEC :str := 'VTP,VR,VM';
SELECT LEVEL AS n
, REGEXP_SUBSTR ( :str
, '[^,]+'
, 1
, LEVEL
) AS str_part
FROM dual
CONNECT BY LEVEL <= 1 + REGEXP_COUNT (:str, ',')
I'm just guessing that your original string doesn't include single-quotes after VR or before VM. If it does, you can use TRIM to remove them from the string passed back by REGEXP_SUBSTR. -
Turning parts of a string into rows in another table
I need to extract unit codes that are stored in a string into rows in a new table as below
From:
Set_cd sequence_number rule_text
KP106A 15432 {1234,4567,8910,1567}
To:
Set_cd sequence_number unit
KP106A 15432 1234
KP106A 15432 4567
KP106A 15432 8910
KP106A 15432 1567
The strings will be of varying lengths but the layout will always be the same with the curley brackets and commas.
Any ideas please?
Thanx
Rob.
Edited by: Rob Mc on Sep 23, 2009 2:38 PMSomething like this ->
satyaki>
satyaki>select * from v$version;
BANNER
Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
PL/SQL Release 10.2.0.1.0 - Production
CORE 10.2.0.1.0 Production
TNS for Linux: Version 10.2.0.1.0 - Production
NLSRTL Version 10.2.0.1.0 - Production
Elapsed: 00:00:00.03
satyaki>
satyaki>
satyaki>with ta_tab
2 as
3 (
4 select 'KP106A' set_cd, 15432 sequence_number, '{1234,4567,8910,1567}' rule_text from dual
5 )
6 select set_cd,
7 sequence_number,
8 REGEXP_SUBSTR (replace(replace(rule_text,'{',''),'}',''), '[^,]+', 1, level) rule_part
9 from ta_tab
10 connect by level <= (
11 select length(regexp_replace(replace(replace(rule_text,'{',''),'}',''),'[^,]*'))+1
12 from ta_tab
13 );
SET_CD SEQUENCE_NUMBER RULE_PART
KP106A 15432 1234
KP106A 15432 4567
KP106A 15432 8910
KP106A 15432 1567
Elapsed: 00:00:01.02
satyaki>
satyaki>Regards.
Satyaki De. -
Convert comma separated string in rows
Dear Gurus,
I want to convert comma separated string in rows so as to insert in collection.
e.g. string 1234,2323,23232,2343,34234
Above string should be converted in rows so as to insert in table or collection
Thanks in advance
SanjeevOr slight variation...
SQL> ed
Wrote file afiedt.buf
1 with t as (select '1234,2323,23232,2343,34234' as txt from dual)
2 --
3 select REGEXP_SUBSTR (txt, '[^,]+', 1, level)
4 from t
5* connect by REGEXP_SUBSTR (txt, '[^,]+', 1, level) is not null
6 /
REGEXP_SUBSTR(TXT,'[^,]+',
1234
2323
23232
2343
34234... so it doesn't have to work out how many levels it needs to do, it just keeps going until it get's a no-value (of course that assumes that there is always a value between each comma) -
Substitution String in Row Template order dependant
Hi Folks,
This questions is related to an earlier Complex Detail Report Layout: Can it be done? about building a complex row template (thanks for your help, Vikas!).<br><br>
Having built the row template (Named Columns) and tested it in a separate application, I have been preparing to incorporate it into the target application. (Here's a screen shot of the work in progress.) I decided to see if I could use column aliases with the substitution strings and so added an alias to the query for the report.<br><br>
Strange values appeared (like a "Y" for a Project Name) and initially I thought the aliases wouldn't work, so I backed the change out. However, it was now quite apparent that the substitution strings were not taking their values from the column names, as I expected. I was able to put the values in the correct place by modifying the order of the columns selected in the query.<br><br>
Am I misunderstanding? Shouldn't the order of the columns in the select statement be irrelevant when named columns are used? <br><br>
Since the order in the query is NOT the order displayed in the template, and I have nearly 30 fields, (many of which are dates, and I couldn't possible guess which is which if the substitution doesn't work properly), it seems important to understand how to ensure the proper values appear in the report.<br><br>
Many thanks for your help,<br><br>
PetieI take it back. This is whacked. Please take a look at the picture (http://tinypic.com/view/?pic=nygyu0)
OK, I had a select statement:
select ps.project_name, ps.project_manager, ps.gts_dependant, ps.gxp_relevant from project_status ps, eprs_program p
where
ps.program_id = p.id and
p.program_number = :P6_PROGRAM_NUMBERThis populated the fields #PROJECT_NAME#, #PROJECT_MANAGER#, etc. properly.
I even switched the order around and put the ps.project_manager ahead of the ps.project_name and template still worked.
I restored the order and checked again. All is good.
I changed the query and added an alias like so:
select ps.project_name as "PROJ_NAME", ps.project_manager, ps.gts_dependant, ps.gxp_relevant from ...The report showed the substitution string "#PROJECT_NAME#" (as expected, because the column was now aliased.) So this is good.
I went to the row template definition and changed the substitution string #PROJECT_NAME# to #PROJ_NAME# to match the query -- and the substitution strings broke again!
The report template now behaves as described earlier; being position dependant. Now I suspect that this is a bug, and not something caused by my mucking around.
I would greatly appreciate your thoughts on the matter and potential workaround. At this point, I will likely delete the region and try creating a new region. I would hate to loose the whole page, the top part was a lot of effort. <sigh>
Thanks,
Petie -
How to convert column with delimited string into rows
I have a string value in a single column, delimited by colon. The number of items in the string is variable. I need to select the data from this column into separate rows based on the delimiter. I can write a function with a loop but if there is a way to do this in SQL it would be better.
Table contains a column with data value:
12:130:1400
And I want to select data and return as:
12
130
1400
This in in Oracle 9i.
Please don't post "look for pivot or transpose in the forum" as that is not a helpful answer (I have already done that).
Thanks!
Message was edited by:
splinternetSQL> create table mytable (id,value)
2 as
3 select 1, '12:130:1400' from dual union all
4 select 2, '483' from dual union all
5 select 3, '1:2:3:4:5:6:77:888' from dual union all
6 select 4, null from dual
7 /
Tabel is aangemaakt.
SQL> select id
2 , trim(':' from v) value
3 , substr
4 ( v
5 , instr(v,':',1,t.column_value) + 1
6 , instr(v,':',1,1 + t.column_value)
7 - instr(v,':',1,t.column_value) - 1
8 ) part
9 from ( select id, ':' || value || ':' v from mytable ) m
10 , table
11 ( cast
12 ( multiset
13 ( select level l
14 from dual
15 connect by rownum <= length(m.v) - length(replace(m.v,':')) - 1
16 )
17 as sys.dbms_debug_vc2coll
18 )
19 ) t
20 order by m.id
21 , t.column_value
22 /
ID VALUE PART
1 12:130:1400 12
1 12:130:1400 130
1 12:130:1400 1400
2 483 483
3 1:2:3:4:5:6:77:888 1
3 1:2:3:4:5:6:77:888 2
3 1:2:3:4:5:6:77:888 3
3 1:2:3:4:5:6:77:888 4
3 1:2:3:4:5:6:77:888 5
3 1:2:3:4:5:6:77:888 6
3 1:2:3:4:5:6:77:888 77
3 1:2:3:4:5:6:77:888 888
4
13 rijen zijn geselecteerd.Regards,
Rob. -
Using a comma seprated string as rows
i hv a column in which i store comma seprated name, i have to show them as rows in a report..
plz helpAs with most things, it depends greatly on your Oracle version (you should always post this information).
In release 11 here's a neat method.
http://laurentschneider.com/wordpress/2009/07/select-from-column-separated-list.html
In release 10 there's REGEXP
http://nuijten.blogspot.com/2009/07/splitting-comma-delimited-string-regexp.html
And it looks like you've been given a pre-10 answer already. -
Retrive data from string to rows
i am using oracle 10g release 2
having table structure like this
product_name keywords brands
cctv eg,ee,ec dealer,retailer
laptop ct,acesso menu,servece
i want the result somyhing like this
cctv eg
cctv ee
cctv ee
cctv dealer
cctv retailer
laptop elect
laptop acesso
laptop menu
laptop acessoservece
its argent plz help me as soon as possible
thanks in advance
Edited by: Jagan on 06-Dec-2011 20:38SQL> with t as (
select 'cctv' product_name, 'eg,ee,ec' keyword, 'dealer, retailer' brands from dual union all
select 'laptop' product_name, 'ct,acesso' keyword, 'menu,servece' brands from dual
select product_name, regexp_substr (keyword || ',' || brands, '\w+', 1, level) keyword_brand
from t
connect by level <= length (keyword || ',' || brands) - length (replace (keyword || ',' || brands, ',')) + 1
and product_name = prior product_name
and prior sys_guid () is not null
PRODUCT_NAME KEYWORD_BRAND
cctv eg
cctv ee
cctv ec
cctv dealer
cctv retailer
laptop ct
laptop acesso
laptop menu
laptop servece
9 rows selected. -
How to split a delimited string into rows
Hi Everyone,
I have a field in my EMPLOYEE table named "OLD_USER_IDS" which stores all the old system ID's that the employee was once assigned to. This field is comma separated like so: "USERID1,USERID2,USERID3". My question is: how can I write a SELECT query that splits each individual User ID into its own row?
For example:
EMP_ID USER_ID
10 USERID1
10 USERID2
12 USERID3
15 USERID4
15 USERID5
15 USERID6
Thank You
-SamI think you should search this forum first for similar questions. I keep track of some interesting stuffs posted in this forum in a file, and from that
WITH t AS (SELECT 'USER1,USER2,USER3' str FROM DUAL
select substr(str,
decode(level,
1,
1,
instr(str, ',', 1, level - 1) + 1),
decode(instr(str, ',', 1, level),
0,
length(str),
instr(str, ',', 1, level) -
decode(level,
1,
0,
instr(str, ',', 1, level - 1)) - 1)) the_value
from (select str from t)
connect by level <=
length(str) - length(replace(str, ',')) + 1; -
I have a table that contains unit rules with one column containing the unit code and another containing the rule text eg.
Unit Code xyz
Rule Text Unit was previously coded {20017, A1537, A2524}
I need to list the old codes in a new table in seperate rows.
Any ideas please?
Thanx
Rob.MJ
The column names are:
Unit_cd || Rule_text
xyz || Unit was previously coded {20017, A1537, A2524}
Output I would like is:
Unit_cd || Prevoius_unit_cd
xyz || 20017
xyz || A1537
xyz || A2524
Not all rules have three valuse, most are single values and some even more.
Thanx
Rob.
Edited by: Rob Mc on Aug 29, 2008 2:52 PM
Edited by: Rob Mc on Aug 29, 2008 2:54 PM
Edited by: Rob Mc on Aug 29, 2008 2:55 PM -
Comma separated string in rows
Hi All,
I have one table
select * from abcd;
No err
1 rishi,rahul
2 rishi,ak
I want output like:
No ERR
1 rishi
1 rahul
2 rishi
2 ak
i am using the below query for this:
select no,regexp_substr(err,'[^,]+', 1, level) from abcd
connect by regexp_substr(err, '[^,]+', 1, level) is not null
but this query is giving me output:
1
rishi
1
rahul
2
ak
2
rishi
1
rahul
2
ak
if i am using distinct then only desired output is coming.
select distinct no,regexp_substr(err,'[^,]+', 1, level) from abcd
connect by regexp_substr(err, '[^,]+', 1, level) is not null
but i don't want to use distinct because my table has millions of rows and err contains comma separated varchar(6000);
please help me.Something like this?
SQL> ed
Wrote file afiedt.buf
1 WITH table_x AS(
2 SELECT 1 id, 'rishi,rahul' str FROM dual UNION ALL
3 SELECT 2 id, 'rishi,ak' str FROM dual
4 )
5 SELECT id,
6 REGEXP_SUBSTR (str,
7 '[^,]+',
8 1,
9 LEVEL)
10 --LEVEL,
11 --SYS_GUID ()
12 FROM table_x
13 CONNECT BY LEVEL <= LENGTH (REGEXP_COUNT (str, ',')) +1
14 AND PRIOR id = id
15 AND PRIOR Sys_Guid() IS NOT NULL
16* ORDER BY id, LEVEL
SQL> /
ID REGEXP_SUBS
1 rishi
1 rahul
2 rishi
2 ak
Trick here is: the usage of SYS_GUID() i.e. System Global Unique Identifier.
Alternative to this, can also use DBMS_RANDOM.value() here.
Read more here - https://forums.oracle.com/thread/2526535
HTH
-- Ranit -
Pipe delimiter string into rows using regular expression
hi Can anyone please help writing pipe' l 'delimiter values to rows
sample data 'something1|something2|something3'
i tried with below query
SELECT LEVEL,
TRIM ('"' FROM RTRIM (REGEXP_SUBSTR ('something1|something2|something3' || '|',
'".*?"||[^|]*|',
1,
LEVEL
'|'
) sub_str
FROM dual
CONNECT BY LEVEL <= LENGTH (REGEXP_REPLACE ('something1|something2|something3' , '".*?"|[^|]*')) + 1SQL> ed
Wrote file afiedt.buf
1 with t as (select 'something1|something2|something3' as txt from dual)
2 -- end of sample data
3 select REGEXP_SUBSTR (txt, '[^|]+', 1, level)
4 from t
5* connect by level <= length(regexp_replace(txt,'[^|]*'))+1
SQL> /
REGEXP_SUBSTR(TXT,'[^|]+',1,LEVE
something1
something2
something3
SQL> -
Re: Convert single column string to rows (CSV)
Hi All
I would appreciate some help here ... i am sure it is simple for many but the research i have done seems to ask for function that don't work in the db i am in.: 10.2.0.5.0
Query is :
SELECT '348419,348420,348421' from DUAL;
Would like output to be:
select from tb1;*
output:
348419
348420
348421Something like this...
Ranit>> select * from a1;
DAT
348419,348420,348421
Ranit>> select RTRIM(regexp_substr(dat,'(,)?[^,]+(,)?',1,level),',')
2 from a1
3 connect by level <= regexp_count(dat,'[,]')+1;
RTRIM(REGEXP_SUBSTR(DAT,'(,)?[^,]+(,)?',1,LEVEL),',')
348419
348420
348421 -
JTable with row header plus value extraction from headers
Hi, I am trying to do the following:
Short Version-
1. Create a table that has both row and column headers
2. Allow the user to mouse over any of these headers such that doing so will display an image I have produced on a panel. (I already know how to create the image and how to display it, I'm just not sure how to associate it with a particular row or column header)
3. Make the row headers look as much as possible like the column headers.
Slightly Longer Version-
Column headers will be labled A-H (maximum) while row headers will be labled 1-12 (maximum). Either can be less, however, depending on user input. After the table has been realized, the user will move the mouse over say, header 'H' and when they do, a JPEG image will appear on another panel and a tooltip will appear above the cell showing a formula. This happens when either row or column headers are moused over.
Currently, I am using the following code from the O'reilly Swing book as a baseline for experimentation but any help you can offer will be appreciated. I'm fairly new to the JTable world... :-(
TableModel tm = new AbstractTableModel(){
String data[] = {"", "a", "b", "c", "d", "e"};
String headers [] = {"Row #", "Column1", "Column2", "Column3", "Column4", "Column5"};
public int getColumnCount(){ return data.length;}
public int getRowCount() { return 1000;}
public String getColumnName(int col){ return headers[col];}
public Object getValueAt(int row, int col){
return data[col] + row;
//creates a column model for the main table. This model ignores the first
//column added and sets a minimum width of 150 pixels for all others
TableColumnModel cm = new DefaultTableColumnModel(){
boolean first = true;
public void addColumn(TableColumn tc){
if(first) {first = false; return;}
tc.setMinWidth(150);
super.addColumn(tc);
//Creates a column model that will serve as the row header table. This model
//picks a maxium width and stores only the first column
TableColumnModel rowHeaderModel = new DefaultTableColumnModel(){
boolean first = true;
public void addColumn(TableColumn tc){
if(first) {
tc.setMaxWidth(tc.getPreferredWidth());
super.addColumn(tc);
first = false;
JTable grid = new JTable(tm, cm);
//set up the header column and hook it up to everything
JTable headerColumn = new JTable(tm, rowHeaderModel);
grid.createDefaultColumnsFromModel();
headerColumn.createDefaultColumnsFromModel();
//make sure the selection between the main table and the header stay in sync
grid.setSelectionModel(headerColumn.getSelectionModel());
headerColumn.setBorder(BorderFactory.createEtchedBorder());
headerColumn.setBackground(Color.lightGray);
headerColumn.setColumnSelectionAllowed(false);
headerColumn.setCellSelectionEnabled(false);
JViewport jv = new JViewport();
jv.setView(headerColumn);
jv.setPreferredSize(headerColumn.getMaximumSize());
//to make the table scroll properly
grid.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//have to manually attach row headers but after that, the scroll pane
//keeps them in sync
JScrollPane jsp = new JScrollPane(grid);
jsp.setRowHeader(jv);
jsp.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, headerColumn.getTableHeader());
gridPanel.add(jsp, BorderLayout.NORTH);There a number of nice examples on JTable: http://www.senun.com/Left/Programming/Java_old/Examples_swing/SwingExamples.html
Hope you could find something suitable ...
Regards,
Anton.
Maybe you are looking for
-
I am no longer able to drag and drop my downloaded files
in yahoo. i, on a daily basis receive about 10 pdf documents and several .dxf files. also autocad .dwg files and jpg files. pretty much any file i have to work with comes to me in my email. i used to be able to select the file, then download it. afte
-
JDBC to Idoc scenario. Pls help
Hi All, I have JDBC (Oracle erp application System 1 ) -- SAP PI (System 2) -- SAP ECC (System 2) 1. Please let me know all the steps I need to do so that I can access the database of (Oracle System 1) in (SAP PI System 2) using JDBC Sender Adap
-
Identifying separate cel phone names in my contacts
In many cases I have two or more cel numbers within individual contacts in my Outlook 2007. to aid in calling the correct one I have added their name after their number (ie. Tom) in the same field & it synced just fine with my previous HTC WM 6.1 pho
-
RWD page goes blank when you disable JS
I have created a simple RWD app in apex.oracle.com using Theme25 http://apex.oracle.com/pls/apex/f?p=606060:1:0 I wanted to see, how it performs if I disable javascript. I was shocked I just got a blank page. RWD, is it not a progressive enhancement?
-
Can't watch video on Safari or Firefox on OS X Tiger?
Hello again, How can one go about installing plug-ins for Firefox 2.0 and Safari? I installed RealPlayer 10 and during the installation it would install the appropriate plug-ins into my browsers... This is the contents of my ~/Library/Internet Plug-i