Replacing one column value between two rows..help??
HI,
I have table T
it has five columns, all are in number data type
Col1 and col2 are jointly primary key i.e. they cannot be repeated combined
when i run this query..
SQL> Select * from t
it shows me the data like this
Col1 Col2 Col3 Col4 Col5
1 1 78 58 12.76
2 1 128 446 32.10
3 1 468 566 52.10
4 1 878 58 52.05
5 1 987 348 22.02
... so on.
my requirement is that i want to update this table by replacing the col1 value between any two rows
suppose this is the first row
Col1 Col2 Col3 Col4 Col5
1 1 78 58 12.76
and this is any 2nd row
Col1 Col2 Col3 Col4 Col5
5 1 987 348 22.02
now i want that for first row the value of col1 replaces the value of col1 of 2nd row
and for 2nd row the value of col1 replaces the value of col1 of 1st row
i.e.
Col1 Col2 Col3 Col4 Col5
5 1 78 58 12.76
Col1 Col2 Col3 Col4 Col5
1 1 987 348 22.02
please tell how to achieve this in single query/procedureregards,
Ramis
SQL> create table t (id1 number, id2 number, name varchar2(1));
Table created.
SQL> alter table t add primary key (id1,id2);
Table altered.
SQL> insert into t values(1,1,'A');
1 row created.
SQL> insert into t values(5,1,'B');
1 row created.
SQL> commit;
Commit complete.
SQL> select * from t;
ID1 ID2 N
1 1 A
5 1 B
SQL> var val1 number
SQL> var val2 number
SQL> exec :val1 := 1;
PL/SQL procedure successfully completed.
SQL> exec :val2 := 5;
PL/SQL procedure successfully completed.
SQL> update t set id1 = (:val1 + :val2) - id1 where id1 in (:val1,:val2);
2 rows updated.
SQL> select * from t;
ID1 ID2 N
5 1 A
1 1 B
SQL> rollback;
Rollback complete.
SQL> select * from t;
ID1 ID2 N
1 1 A
5 1 B
SQL> commit;
Commit complete.
SQL> update t set id1 = decode(id1,:val1,:val2,:val1)
2 where id1 in (:val1, :val2);
2 rows updated.
SQL> select * from t;
ID1 ID2 N
5 1 A
1 1 BRgds.
Similar Messages
-
Is it possible to Lock just one column value in a row?
Is it possible to Lock just one column value in a row
A Java Developer has just asked me if it is possible to Lock just one column value in a row in Oracle
select ename from emp where empno=7369 for update;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-DEC-80 800 20
will lock the entire row with empno=7369.
But is it possible to lock one column value from this row, like SAL=800 ?
Edited by: J.Kiechle on Jan 8, 2009 10:45 PMJ.Kiechle wrote:
Is it possible to Lock just one column value in a rowNo. Locking granularity is a row. -
Better approach for checking column values between two different rows
My requirement is to find best Approach to find difference between column values of two different rows.Below I've mentioned two different
approaches I'm thinking of,but I'd like to know is there any other better approach.
version details
SQL> SELECT *
2 FROM V$VERSION;
BANNER
Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
PL/SQL Release 11.1.0.7.0 - Production
CORE 11.1.0.7.0 Production
TNS for Solaris: Version 11.1.0.7.0 - Production
NLSRTL Version 11.1.0.7.0 - ProductionTable creation script
CREATE TABLE R_DUMMY
(CA_ID VARCHAR2(16) NOT NULL ENABLE,
CA_VER_NUM NUMBER(4,2) NOT NULL ENABLE,
BRWR_SHORT_NAME VARCHAR2(25 CHAR),
sic_code number,
FAC_ID VARCHAR2(10) NOT NULL ENABLE
/ insert script
insert into r_dummy (CA_ID, CA_VER_NUM, BRWR_SHORT_NAME, sic_code, FAC_ID)
values ('CA2001/11/0002', 2.00, 'Nandu',1234, 'FA000008');
insert into r_dummy (CA_ID, CA_VER_NUM, BRWR_SHORT_NAME, sic_code, FAC_ID)
values ('CA2001/11/0002', 3.00, 'SHIJU',456, 'FA000008');Desired O/P :
ca_id fac_id column_name previous name after_modification
CA2001/11/0002 FA000008 BRWR_SHORT_NAME Nandu SHIJU
CA2001/11/0002 FA000008 sic_code 1234 456My approach
select ca_id,fac_id,column_name,
decode(column_name,'BRWR_SHORT_NAME',lg_brwr,lg_sic) previous_name ,
decode(column_name,'BRWR_SHORT_NAME',ld_brwr,ld_sic) after_modification
from
select
case
when ld_brwr != lg_brwr then
'BRWR_SHORT_NAME'
when ld_brwr != lg_brwr then
'sic_code'
end
) column_name,ca_id,fac_id,lg_brwr,ld_brwr,ld_sic,lg_sic
from (
select ca_id,fac_id,lag_brwr,ld_brwr,ld_sic,lag_sic
from
Select lead(brwr_short_name,1) over(partition by ca_id,fac_id) ld_brwr,
lag(brwr_short_name,1) over(partition by ca_id,fac_id) lg_brwr,
lead(sic_code,1) over(partition by ca_id,fac_id) ld_sic,
lag(sic_code,1) over(partition by ca_id,fac_id) lg_sic,
ca_id,fac_id
from r_dummy
where (ld_brwr != lg_brwr or ld_sic != lg_sic)
)2nd Approach :
=============
select ca_id,fac_id,column_name,
decode(column_name,'BRWR_SHORT_NAME',lg_brwr,lg_sic) previous_name ,
decode(column_name,'BRWR_SHORT_NAME',ld_brwr,ld_sic) after_modification
from
select
case
when ld_brwr != lg_brwr then
'BRWR_SHORT_NAME'
when ld_brwr != lg_brwr then
'sic_code'
end
) column_name,ca_id,fac_id,lg_brwr,ld_brwr,ld_sic,lg_sic
from (
select ca_id,fac_id,brwr_short_name,sic_code
from
Select ca_id,fac_id,brwr_short_name lg_brwr,sic_code lg_sic
from r_dummy
where ca_ver_num = '2.00'
)o,(
Select ca_id,fac_id,brwr_short_name ld_brwr,sic_code ld_sic
from r_dummy
where ca_ver_num = '3.00'
)n
where 0.ca_id = n.ca_id
and 0.fac_id = n.fac_id
and (ld_brwr != lg_brwr or ld_sic != lg_sic)
)Hi Experts,
I've provided sample data where I'm checking for just two columns viz brwr_short_name ,sic_code,but in real time
I've to check for 8 more columns so please suggest me with a better approach.
I appreciate your precious suggestions.Hi,
Thanks for posting the CREATE TABLE and INSERT statements; that really helps!
Here's one wa. Like your 2nd approach, this uses a self-join:
WITH got_r_num AS
SELECT ca_id
, ROW_NUMBER () OVER ( PARTITION BY ca_id
, fac_id
ORDER BY ca_ver_num
) AS r_num
, brwr_short_name
, TO_CHAR (sic_code) AS sic_code
, fac_id
-- , ... -- Other columns (using TO_CHAR if needed)
FROM r_dummy
, unpivoted_data AS
SELECT *
FROM got_r_num
UNPIVOT INCLUDE NULLS
( txt
FOR column_name IN ( brwr_short_name AS 'BRWR_SHORT_NAME'
, sic_code AS 'SIC_CODE'
-- , ... -- Other columns
SELECT p.ca_id
, p.fac_id
, p.column_name
, p.txt AS previous_name
, a.txt AS after_modification
FROM unpivoted_data p
JOIN unpivoted_data a ON p.ca_id = a.ca_id
AND p.fac_id = a.fac_id
AND p.column_name = a.column_name
AND p.r_num = a.r_num - 1
AND p.txt || 'X' != a.txt || 'X'
ORDER BY a.r_num
;To include other columns, add them in the 2 places where I put the comment "Other columns".
Ca_ver_num can have any values, not just 2.00 and 3.00.
This will show cases where a value in one of the columns changed to NULL, or where NULL changed to a value.
There ought to be a way to do this without a separate sub-query like got_r_num. According to the SQL Language manual, you can put expressions in the UPIVOT ... IN list, but when I tried
... UNPIVOT INCLUDE NULLS
( txt
FOR column_name IN ( brwr_short_name AS 'BRWR_SHORT_NAME'
, TO_CHAR (sic_code) AS 'SIC_CODE'
)I got the error "ORA_00917: missing comma" right after TO_CHAR. Perhaps someone else can show how to eliminate one of the sub-queries. -
Split one column value into two columns using t-sql
Hi All,
I have one varchar column in a table.
Col1
ABC-12C4
BC-A345
CD
XYZ
How to split this into two columns like this using t-sql
Col1 Col2
ABC 12C4
BC A345
CD
XYZ
Thanks,
RH
sqlassuming a static delimiter, and the split will end up with a max of 2 columns, something like this would work. basically you just need to determine where the delimiter is, and then use the left and right functions to find the 2 pieces.
declare @t table(value varchar(10))
insert into @t(value)
values
('ABC-12C4'), ('BC-A345'), ('CD'), ('XYZ')
select
case
when charindex('-', value) != 0 then left(value, charindex('-', value) - 1)
else value
end as col1,
case
when charindex('-', value) != 0 then right(value, len(value) - charindex('-', value))
else ''
end as col2
from @t -
Join all rows bases on one column value
Hi All,
I have requrement like Join all rows bases on one column value, i am not getting how to accomplish that. Here is my requrement. i have table test(id,id_desc) with no key
table:Test
id id_desc
1 desc_a
1 desc_b
1 desc_c
Now the requremnet i have one more table as test1(id,id_desc) here id is primary key. where record i need to insert as
id id_desc
1 desc_a
desc_b
desc_corza wrote:
Hi All,
I have requrement like Join all rows bases on one column value, i am not getting how to accomplish that. Here is my requrement. i have table test(id,id_desc) with no key
table:Test
id id_desc
1 desc_a
1 desc_b
1 desc_c
Now the requremnet i have one more table as test1(id,id_desc) here id is primary key. where record i need to insert as
id id_desc
1 desc_a
desc_b
desc_cI'm guessing you want to pivot the results in TEST and use that to insert into TEST1?
If so this may be useful
http://www.oracle-base.com/articles/misc/StringAggregationTechniques.php -
I need to retrieve the a set of rows in between two rows from a table.
consider employees table and primary key employee_id.
With out using EMPLOYEE_ID column in the where clause or between clause, I need to get the records between 104 and 116 or a set of records between two rows.
Can any one help me in this... i know this is simple but am just a fresher to oracle development... help me grow....
Thanks,
Arunya at last i got the out put... thank guys for thinking with me....
SELECT rownum, employee_id FROM (SELECT rownum, employee_id FROM employees ORDER BY employee_id)
WHERE ROWNUM <=8
MINUS
SELECT rownum, employee_id FROM (SELECT rownum, employee_id FROM employees ORDER BY employee_id) WHERE ROWNUM <= 4 -
JTable - One Column Heading for Two Columns
Can you adjust the default JTable to have one column heading for two columns of data? Is there a simple span command? I've looked at the api for JTable and JTableHeader and didn't see anything, is there something I'm missing? Any help would be appreciated.
What i am trying to accomplish is have column 'E' span 2 columns.
This is my code thus far, however it give the error from my pryor message. I am pretty sure it is because I'm using and Object[][] and a String[] instead of Vectors. What corrections do I need to make in order for my goal of:
[ A ][ B ][ C ][ D ][ E ][ F ][ G ]
[ 1 ][ 2 ][ 3 ][ 4 ][5][6][ 7 ][ 8 ]
Object[][] data = new Object[ROWS][COLUMNS];
String[] columnNames = {"A","B","C","D","E","E","F","G"};
table = new JTable(data, columnNames);
table.setBackground(Color.white);
table.addKeyListener(this);
DefaultTableCellRenderer d = new DefaultTableCellRenderer();
d.setHorizontalAlignment(JLabel.CENTER);
table.setDefaultRenderer(table.getColumnClass(0),d);
for (int i = 0; i < table.getColumnCount(); i++){
TableColumn aColumn = header.getColumnModel().getColumn(i);
TableCellRenderer renderer = aColumn.getHeaderRenderer();
if (renderer == null) {
renderer = new DefaultTableCellRenderer(){
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){
JTableHeader header = table.getTableHeader();
if (header != null) {
setForeground(header.getForeground());
setBackground(header.getBackground());
setFont(header.getFont());
setHorizontalAlignment(JLabel.CENTER);
setText((value == null) ? "" : value.toString());
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
return this;
aColumn.setHeaderRenderer(renderer); -
In BADi , How to pass the values between two Method
Hi Experts,
We have two methods in BADis. How to pass the value between two Methods. Can you guys explain me out with one example...
Thanks & Regards,
Sivakumar SHi Sivakumar!
Create a function group.
Define global data (there is a similiar menu point to jump to the top include).
Create one or two function modules, with which you can read and write the global data.
In your BADI methods you can access the global data with help of your function modules. It will stay in memory through the whole transaction.
Regards,
Christian -
How to display the column header in two rows?
Hi Experts,
I am using ALV_LIST_DISPLAY i neeed to display the column header in two rows.. How can i do that?
Ex: purchase order i need to display "purchase" in one row and "order" in second row.
Thanks in advance,
Sarath.jREPORT zpwtest .
TYPE-POOLS slis .
DATA : layout TYPE slis_layout_alv .
CONSTANTS : c_len TYPE i VALUE 20 .
TYPES : BEGIN OF ty_t100 ,
sprsl TYPE t100-sprsl ,
arbgb TYPE t100-arbgb ,
msgnr TYPE t100-msgnr ,
text TYPE t100-text ,
fline TYPE t100-text ,
END OF ty_t100 .
TYPES : BEGIN OF ty_wrd ,
text TYPE char20 ,
END OF ty_wrd .
DATA : it_t100 TYPE TABLE OF ty_t100 ,
it_sentence TYPE TABLE OF ty_wrd ,
wa_t100 TYPE ty_t100 ,
wa_word TYPE ty_wrd ,
v_repid TYPE syst-repid ,
v_tabix TYPE syst-tabix .
DATA : it_fld TYPE slis_t_fieldcat_alv ,
it_evt TYPE slis_t_event ,
wa_fld TYPE slis_fieldcat_alv ,
wa_evt TYPE slis_alv_event .
INITIALIZATION .
v_repid = sy-repid .
START-OF-SELECTION .
* Get data
SELECT *
INTO TABLE it_t100
FROM t100
WHERE sprsl = 'EN'
AND arbgb = '00' .
LOOP AT it_t100 INTO wa_t100 .
v_tabix = sy-tabix .
CLEAR : it_sentence .
CALL FUNCTION 'RKD_WORD_WRAP'
EXPORTING
textline = wa_t100-text
outputlen = c_len
TABLES
out_lines = it_sentence.
IF NOT it_sentence IS INITIAL .
READ TABLE it_sentence INTO wa_word INDEX 1 .
wa_t100-fline = wa_word-text .
MODIFY it_t100 FROM wa_t100 INDEX v_tabix .
ENDIF.
ENDLOOP.
* Prepare fieldcatelog
CLEAR wa_fld .
wa_fld-fieldname = 'SPRSL' .
wa_fld-ref_tabname = 'T100' .
wa_fld-ref_fieldname = 'SPRSL' .
APPEND wa_fld TO it_fld .
CLEAR wa_fld .
wa_fld-fieldname = 'ARBGB' .
wa_fld-ref_tabname = 'T100' .
wa_fld-ref_fieldname = 'ARBGB' .
APPEND wa_fld TO it_fld .
CLEAR wa_fld .
wa_fld-fieldname = 'MSGNR' .
wa_fld-ref_tabname = 'T100' .
wa_fld-ref_fieldname = 'MSGNR' .
APPEND wa_fld TO it_fld .
CLEAR wa_fld .
wa_fld-fieldname = 'FLINE' .
wa_fld-inttype = 'CHAR' .
wa_fld-outputlen = 20 .
wa_fld-intlen = 20.
wa_fld-seltext_l = 'Text' .
wa_fld-ddictxt = 'L' .
APPEND wa_fld TO it_fld .
* Get event.. we will handle BOFORE and AFTER line output
CALL FUNCTION 'REUSE_ALV_EVENTS_GET'
IMPORTING
et_events = it_evt.
READ TABLE it_evt INTO wa_evt
WITH KEY name = slis_ev_after_line_output .
wa_evt-form = slis_ev_after_line_output .
MODIFY it_evt FROM wa_evt INDEX sy-tabix .
READ TABLE it_evt INTO wa_evt
WITH KEY name = slis_ev_top_of_page .
wa_evt-form = slis_ev_top_of_page .
MODIFY it_evt FROM wa_evt INDEX sy-tabix .
layout-no_colhead = 'X' .
CALL FUNCTION 'REUSE_ALV_LIST_DISPLAY'
EXPORTING
i_callback_program = v_repid
it_fieldcat = it_fld
is_layout = layout
it_events = it_evt
TABLES
t_outtab = it_t100.
* FORM top_of_page *
FORM top_of_page .
uline .
WRITE: / sy-vline ,
10 sy-vline ,
11 'line1' ,
31 sy-vline ,
37 sy-vline ,
58 sy-vline .
WRITE: / sy-vline ,
10 sy-vline ,
11 'line2' ,
31 sy-vline ,
37 sy-vline ,
58 sy-vline .
WRITE: / sy-vline ,
10 sy-vline ,
11 'line3' ,
31 sy-vline ,
37 sy-vline ,
58 sy-vline .
ENDFORM.
* FORM AFTER_LINE_OUTPUT *
FORM after_line_output USING rs_lineinfo TYPE slis_lineinfo .
CLEAR : it_sentence ,
wa_t100 .
READ TABLE it_t100 INTO wa_t100 INDEX rs_lineinfo-tabindex .
CHECK sy-subrc = 0 .
CALL FUNCTION 'RKD_WORD_WRAP'
EXPORTING
textline = wa_t100-text
outputlen = c_len
TABLES
out_lines = it_sentence.
DESCRIBE TABLE it_sentence LINES v_tabix .
CHECK v_tabix > 1 .
LOOP AT it_sentence INTO wa_word FROM 2 .
WRITE: / sy-vline ,
10 sy-vline ,
31 sy-vline ,
37 sy-vline ,
38 wa_word-text ,
58 sy-vline .
ENDLOOP.
ENDFORM . -
Awk - printing a value between two matching regex [SOLVED]
I'm trying to write a script to parse a single line output, but to then only display the value between two matching regex.
I have got it to only display the value between the matching regex, but then it carries on and displays the rest of the line. How do I tell it to stop once the matching value has been printed?
ARTIST=`awk '/Artist/,/Artist/ {gsub(/Artist/, Artist); print}' /home/sapphire/.foobar2000/track_info`
This produces 'Akira Yamaoka Title She Title Album Silent Hill 1 OST Album CurrentTime 0:03 CurrentTime TotalTime 2:01 TotalTime' rather then the desired 'Akira Yamaoka'.
So I guess I'm asking how one would go about terminating the above awk command? Thanks - I know, it'll be something simple - but I'm not experienced with scripting
Last edited by wyvern (2008-04-10 11:37:30)ibendiben wrote:Could you share the file you are extracting the data from?
No problem, and thank you for the help so far
This is what's written each time I update my playing track, no more, no less:
Artist Akira Yamaoka Artist Title Silent Hill Title Album Silent Hill 1 OST Album CurrentTime 0:04 CurrentTime TotalTime 2:51 TotalTime
Single line only, as the plugin won't break up the text into anything more than the one line -
Calculate the variance between two row
Post Author: jane
CA Forum: WebIntelligence Reporting
Hi,
I'm new to BO and wondering whether there is a way to calculate the variance between two rows. I'm working on a report which requires to display the change of two day's data. For instance, I have a table in a format as
Date
Sales Amount
3/12/2008
2300.00
2/12/2008
1280.00
Changed
1020.00
I'd like to display the "Changed" column. Is there a way to do that in BO InfoView? In Excel, you can use the formular by identify the two cells.
Thanks!Post Author: Vinl
CA Forum: WebIntelligence Reporting
I am having the same problem and am steping outside of the box and cannot progress.
Seems to me that you are kind of saying that the only way to get around this is to create an individual object in Designer? I cannot find a way of cementing values as a variable in order for a variance to be created.
I am trying to do it at column level mind you, which should not make that much difference....
Simple SQL database. I have created an object called "Year" which takes a date and converts it to a year. I then have another object created "Total sales", put the 2 in a table get the right results...try and create a year on year variance from that...no chance...
Used to work ok...? -
Hello,
I need to add space between rows. Please let me know how to go about.
I have a messgeComponentLayout Region, i am trying to create a space between two rows.
Presently it is as follows:
Vacation Plan
Sick Plan
I need as follows:
Vacation Plan
Sick Plan
Please let me know how to go about.
Thanks!The foll. is the region, how do i incorporate the rowLayout as suggested in the discussion. Please let me know.
<?xml version = '1.0' encoding = 'UTF-8'?>
<!-- dbdrv: exec java oracle/jrad/tools/xml/importer XMLImporter.class java &phase=dat+24 checkfile:~PROD:~PATH:~FILE &fullpath:~PROD:~PATH:~FILE -username &un_apps -password &pw_apps -dbconnection &jdbc_db_addr -userId "1" -rootPackage /oracle/apps/~PROD -rootdir &fullpath:~PROD:mds:directory -->
<oa:header version="9.0.3.8.12_1330" xml:lang="en-US" xmlns:oa="http://xmlns.oracle.com/oa" xmlns:jrad="http://xmlns.oracle.com/jrad" xmlns:ui="http://xmlns.oracle.com/uix/ui" xmlns:user="http://xmlns.oracle.com/jrad/user" xmlns="http://xmlns.oracle.com/jrad" file-version="$Header$" text="Year to Date Accruals and Time Taken (total hrs.):" amDefName="xbol.oracle.apps.xbol.selfservice.loa.server.YtdAM">
<ui:contents>
<oa:messageComponentLayout controllerClass="xbol.oracle.apps.xbol.selfservice.loa.webui.MainRNCO" rows="7" columns="2" amDefName="xbol.oracle.apps.xbol.selfservice.loa.server.YtdAM" id="Main">
<ui:contents>
<oa:messageStyledText id="VaPlCo" prompt="US Vacation Carry Over" viewName="VacPlAcVO1" viewAttr="VacationCarryOver" styleClass="OraDataText"/>
<oa:messageStyledText id="VaPlAc" prompt="US Vacation Plan Accrual" viewName="VacPlAcVO1" viewAttr="UsVacationPlan" styleClass="OraDataText"/>
<oa:messageStyledText id="VaTk" prompt="Vacation Taken" viewName="VacPlAcVO1" viewAttr="VacationPlan" styleClass="OraDataText"/>
<oa:messageStyledText id="FlPlAc" prompt="US Floating Holiday Plan Accrual" viewName="VacPlAcVO1" viewAttr="UsFloatingHolidayPlan" styleClass="OraDataText"/>
<oa:messageStyledText id="FlTk" prompt="Floating Holiday Taken" viewName="VacPlAcVO1" viewAttr="FloatingHolidayPlan" styleClass="OraDataText"/>
<oa:messageStyledText id="AcBaTk" prompt="Accrual Bank Taken" viewName="VacPlAcVO1" viewAttr="AccrualBankPlan" styleClass="OraDataText"/>
<oa:messageStyledText id="item2"/>
<oa:messageStyledText id="SiPlCo" prompt="US Sick Plan Carry Over" viewName="VacPlAcVO1" viewAttr="SickCarryOver" styleClass="OraDataText"/>
<oa:messageStyledText id="SiPlAc" prompt="US Sick Plan Accrual" viewName="VacPlAcVO1" viewAttr="UsSickPlan" styleClass="OraDataText"/>
<oa:messageStyledText id="SiTk" prompt="Sick Taken" viewName="VacPlAcVO1" viewAttr="SickPlan" styleClass="OraDataText"/>
<oa:messageStyledText id="item1" rendered="true"/>
<oa:messageStyledText id="PePlAc" prompt="US Personal Leave Plan Accrual" viewName="VacPlAcVO1" viewAttr="UsPersonalLeavePlan" styleClass="OraDataText"/>
<oa:messageStyledText id="PeTk" prompt="Personal Taken" viewName="VacPlAcVO1" viewAttr="PersonalLeavePlan" styleClass="OraDataText"/>
</ui:contents>
</oa:messageComponentLayout>
</ui:contents>
</oa:header> -
Concatenate a column value across multiple rows - PDW
We are using PDW based on SQL2014. We require an efficient logic on how to concatenate a column value across multiple rows. We have the following table
T1
(CompanyID, StateCD)
Having following rows:
1 NY
1 NJ
1 CT
2 MA
2 NJ
2 VA
3 FL
3 CA
We need a code snippet which will return following result set:
1
CT,NJ,NY
2
MA,NJ,VA
3
CA,FL
We have tried built-in function STUFF with FOR XML PATH clause and it is not supported in PDW. So, we need a fast alternative.Hi Try this:
SELECT * INTO #ABC
FROM
SELECT 1 AS ID,'NY' AS NAME
UNION
SELECT 1 AS ID,'NJ' AS NAME
UNION
SELECT 1 AS ID,'CT' AS NAME
UNION
SELECT 2 AS ID,'MA' AS NAME
UNION
SELECT 2 AS ID,'NJ' AS NAME
UNION
SELECT 2 AS ID,'VA' AS NAME
UNION
SELECT 3 AS ID,'FL' AS NAME
UNION
SELECT 3 AS ID,'CA' AS NAME
)A
CREATE TABLE ##CDB (ID INT, NAME NVARCHAR(800))
DECLARE @TMP VARCHAR(MAX),
@V_MIN INT,
@V_MAX INT,
@V_COUNT INT
SELECT @V_MIN=MIN(ID),@V_MAX=MAX(ID) FROM #ABC
SET @V_COUNT=@V_MIN
WHILE @V_COUNT<=@V_MAX
BEGIN
SET @TMP = '' SELECT @TMP = @TMP + CONVERT(VARCHAR,NAME) + ', ' FROM #ABC
WHERE ID=@V_COUNT
INSERT INTO ##CDB (ID, NAME) SELECT @V_COUNT AS ID ,CAST(SUBSTRING(@TMP, 0, LEN(@TMP)) AS VARCHAR(8000)) AS NAME
SET @V_COUNT=@V_COUNT+1
END
SELECT * FROM ##CDB
OR
SELECT * INTO #ABC
FROM
SELECT 1 AS ID,'NY' AS NAME
UNION
SELECT 1 AS ID,'NJ' AS NAME
UNION
SELECT 1 AS ID,'CT' AS NAME
UNION
SELECT 2 AS ID,'MA' AS NAME
UNION
SELECT 2 AS ID,'NJ' AS NAME
UNION
SELECT 2 AS ID,'VA' AS NAME
UNION
SELECT 3 AS ID,'FL' AS NAME
UNION
SELECT 3 AS ID,'CA' AS NAME
UNION
SELECT 5 AS ID,'LG' AS NAME
UNION
SELECT 5 AS ID,'AP' AS NAME
)A
CREATE TABLE ##CDB (ID INT, NAME NVARCHAR(800))
DECLARE @TMP VARCHAR(MAX),
@V_MIN INT,
@V_MAX INT,
@V_COUNT INT
SELECT @V_MIN=MIN(ID),@V_MAX=MAX(ID) FROM #ABC
SET @V_COUNT=@V_MIN
WHILE @V_COUNT<=@V_MAX
BEGIN
SET @TMP = '' SELECT @TMP = @TMP + CONVERT(VARCHAR,NAME) + ', ' FROM #ABC
WHERE ID=@V_COUNT
SELECT @V_COUNT AS ID ,CAST(SUBSTRING(@TMP, 0, LEN(@TMP)) AS VARCHAR(8000)) AS NAME INTO #TEMP
INSERT INTO ##CDB (ID, NAME) SELECT ID, NAME FROM #TEMP WHERE NAME<>''
DROP TABLE #TEMP
SET @V_COUNT=@V_COUNT+1
END
SELECT * FROM ##CDB
Thanks Shiven:) If Answer is Helpful, Please Vote -
Reg : Concatenation of a column value with multiple rows... URGENT
Hello,
Could any of u help me in concatenating a column value with
multiple rows ???
For ex : I've the following data from emp table :
DEPTNO ENAME
10 KING'S
30 BLAKE
10 CLARK
10 TOM JONES
30 ALLEN
30 JAMES
20 SMITH
20 SCOTT
20 MILLER
10 MILLER
20 rajeev
I want the following output :
deptno Concat_value
10 KING'S,CLARK,TOM JONES,MILLER
20 Rajeev,MILLER,SMITH,SCOTT
30 BLAKE,ALLEN,JAMES
Thanks in Advance,
SriniHello Naveen,
Thanks for ur answer. But I need a single SQL query for getting
what I want. I know the solution in PL/SQL.
Please try it in a single SQL....
Thanks again,
Srini -
How To Concatenate Column Values from Multiple Rows into a Single Column?
How do I create a SQL query that will concatenate column values from multiple rows into a single column?
Last First Code
Lesand Danny 1
Lesand Danny 2
Lesand Danny 3
Benedi Eric 7
Benedi Eric 14
Result should look like:
Last First Codes
Lesand Danny 1,2,3
Benedi Eric 7,14
Thanks,
David JohnsonStarting with Oracle 9i
select last, first, substr(max(sys_connect_by_path(code,',')),2) codes
from
(select last, first, code, row_number() over(partition by last, first order by code) rn
from a)
connect by last = prior last and first = prior first and prior rn = rn -1
start with rn = 1
group by last, first
LAST FIRST CODES
Lesand Danny 1,2,3
Benedi Eric 7,14Regards
Dmytro
Maybe you are looking for
-
Any help is appreciated. I'd hate to have to return Apple TV because I can't get it to sync and be forced to use iTunes Match. The Apple ID's are the same and the internet connection works.
-
Load a vhd on Windows Server 2012?
All the engines look up the wrong thing. I have a .vhd I want to load on my windows 2012 server(Hyper-V non-gui machine loaded by support co.) so I can run it to demonstrate software contained in the vhd. The OS of the vhd is Server 2008 r2 but that
-
Any solutions on how to delete the "ghost songs" ? P.S I deleted all the songs from itunes and restored from backup but that did nothing
-
Restricting the values in Drop Down list for ESS application
Hello Experts, We are trying to restrict the values in the drop down list box for payment method field for direct deposit iview. Here Payment is the Zlsch field. here we are trying to have only 3 vlaues in the drop down. Do I have to do it from java
-
Not getting the option to deauthorise my old computer which isnt here anymore and then authorise my new computer. What do I try next?