Convert rows to columns and put line break in between using t-sql
Hi,
I have a table with 5 columns..and my source data looks like this..
RecordID ID Display AddressType EmailAddress
1 1 GeneratedBy From
[email protected]
1 1 ReceivedBy To
[email protected]
1 1 ReceivedBy To
[email protected]
2 1
3 1 GeneratedBy From
[email protected]
3 1 GeneratedBy From [email protected]
3 1 ReceivedBy To
[email protected]
I need t-sql to show output as..
RecordID ID FullDisplay
1 1 GeneratedBy From -
[email protected] < CHAR(13) - Need Line Break here so that it goes to 2nd line>
ReceivedBy To -
[email protected] ; To -
[email protected]
2 1 Null
3 1 GeneratedBy From -
[email protected] ; From -
[email protected] < CHAR(13) - Need Line Break here so that it goes to 2nd line>
ReceivedBy To -
[email protected]
Display field will have 3 values - "GeneratedBy" , "ReceivedBy" or Null
AddresType field will have 3 values - "From" , "To" and Null.
In the above example, Those 7 records belongs to ID=1.
Whenever RecordID is same I want to show everything in one line with line breaks in between.
In the above example RecordID=1 has 3 rows, display it as 1 row. But Whenever 'ReceivedBy' is there for same recordID put a line break before "ReceivedBy"
create Statement:
Create Table SampleTest
(RecordID int null, ID int null , Dispplay varchar(20) null, AddressType varchar(6) null , EmailAddress Varchar(25) null)
Insert Statement:
Insert into SampleTest (RecordID ,ID,Display,AddressType,EmailAddress) values (1,1,'GeneratedBy','From','[email protected]')
Insert into SampleTest (RecordID ,ID,Display,AddressType,EmailAddress) values (1,1,'ReceivedBy','To','[email protected]')
Insert into SampleTest (RecordID ,ID,Display,AddressType,EmailAddress) values (1,1,'ReceivedBy','To','[email protected]')
Insert into SampleTest (RecordID ,ID,Display,AddressType,EmailAddress) values (2,1, Null,Null,Null)
Insert into SampleTest (RecordID ,ID,Display,AddressType,EmailAddress) values (3,1,'GeneratedBy','From','[email protected]')
Insert into SampleTest (RecordID ,ID,Display,AddressType,EmailAddress) values (3,1,'GeneratedBy','From','[email protected]')
Insert into SampleTest (RecordID ,ID,Display,AddressType,EmailAddress) values (3,1,'ReceivedBy','To','[email protected]')
Thanks!
sql
Try below
drop table SampleTest
GO
Create Table SampleTest
(RecordID int null, ID int null , Display varchar(20) null, AddressType varchar(6) null , EmailAddress Varchar(25) null)
--Insert Statement:
Insert into SampleTest (RecordID ,ID,Display,AddressType,EmailAddress) values (1,1,'GeneratedBy','From','[email protected]')
Insert into SampleTest (RecordID ,ID,Display,AddressType,EmailAddress) values (1,1,'ReceivedBy','To','[email protected]')
Insert into SampleTest (RecordID ,ID,Display,AddressType,EmailAddress) values (1,1,'ReceivedBy','To','[email protected]')
Insert into SampleTest (RecordID ,ID,Display,AddressType,EmailAddress) values (2,1, Null,Null,Null)
Insert into SampleTest (RecordID ,ID,Display,AddressType,EmailAddress) values (3,1,'GeneratedBy','From','[email protected]')
Insert into SampleTest (RecordID ,ID,Display,AddressType,EmailAddress) values (3,1,'GeneratedBy','From','[email protected]')
Insert into SampleTest (RecordID ,ID,Display,AddressType,EmailAddress) values (3,1,'ReceivedBy','To','[email protected]')
with CTE1 as
select ROW_NUMBER() over(PARTITION by RecordID ,ID,Display order by EmailAddress)rno,* From SampleTest
), CTE2 as (
select RecordID ,ID,'GeneratedBy '+ STUFF(( SELECT '; From - ' + EmailAddress AS [text()]
FROM CTE1 b
WHERE
a.RecordID=b.RecordID and a.ID=b.ID and b.Display = 'GeneratedBy'
FOR XML PATH('')
), 1, 2, '' ) GeneratedBy,
'ReceivedBy '+ STUFF(( SELECT '; To - ' + EmailAddress AS [text()]
FROM CTE1 b
WHERE
a.RecordID=b.RecordID and a.ID=b.ID and b.Display = 'ReceivedBy'
FOR XML PATH('')
), 1, 2, '' ) ReceivedBy
From CTE1 a
group by RecordID ,ID
select RecordID ,ID,GeneratedBy +CHAR(13)+ ReceivedBy as FullDisplay from CTE2
Thanks
Saravana Kumar C
Similar Messages
-
Convert row to columns and bind with same ID
Hi All,
I have a table with 2 columns - ID as Int and ClientID as Varchar(max)
ID ClientID
1 123,784
2 342,891,322
3 111
4 982,543,212,453
I want t-sql to get output like this..Whenever there is a comma, split them and bind it to same ID.
ID ClientID
1 123
1 784
2 342
2 891
2 322
3 111
4 982
4 543
4 212
4 453
Create statement:
Create Table Sample
( ID Int null , ClientID varchar(max) null)
Insert statement:
Insert into sample (ID,ClientID) Values (1,'123,784')
Insert into sample (ID,ClientID) Values (2,'342,891,322')
Insert into sample (ID,ClientID) Values (3,'111')
Insert into sample (ID,ClientID) Values (4,'982,543,212,453')
Thanks,
RH
sqlYou can also do this using a user defined table valued function like this:
create FUNCTION [dbo].[ufn_SplitString_Separator](@InputStr VARCHAR(max), @Separator VARCHAR(1))
RETURNS @tmpTable TABLE (OutputStr VARCHAR(max))
AS BEGIN
DECLARE @TmpPOS integer
SET @TmpPOS = CHARINDEX(@Separator,@InputStr)
WHILE @TmpPos > 0 BEGIN
IF @TmpPos > 0 BEGIN
INSERT INTO @tmpTable VALUES (LTRIM(RTRIM(SUBSTRING(@InputStr,1,@TmpPos-1))))
SET @InputStr = SUBSTRING(@InputStr, @TmpPOS + 1, LEN(@InputStr) - @TmpPos)
SET @TmpPOS = CHARINDEX(@Separator,@InputStr)
END ELSE BEGIN
INSERT INTO @tmpTable VALUES (LTRIM(RTRIM(@InputStr)))
SET @TmpPos = 0
END
END
IF LEN(@InputStr) > 0 BEGIN
INSERT INTO @tmpTable VALUES (LTRIM(RTRIM(@InputStr)))
END
RETURN
END
And get the results:
DECLARE @Sample TABLE ( ID Int null , ClientID varchar(max) null)
Insert into @sample (ID,ClientID)
VALUES
(1,'123,784'),(2,'342,891,322'),(3,'111'),(4,'982,543,212,453')
select id, outputstr as clientid from @sample cross apply dbo.[ufn_SplitString_Separator](clientid,',')
"If there's nothing wrong with me, maybe there's something wrong with the universe!" -
Convert row to column and delete id which repeating.
In target table i should load winner_id first and then respective looser_id's of all winner_id.
input
table name:merger
sno winner_id looser_id
1 100 200
2 304 500
3 100 400
4 456 700
5 100 987
my output should be as below
100
200
400
987
304
456979693 wrote:
if i use union i will not get ids in sequence.So you want all distinct winners first followed by all distinct loosers. I'll assume if same id is both winner & looser it will appear once as a winner. If so, use:
with t as (
select winner_id id,
1 weight
from merger
union all
select looser_id,
2 weight
from merger
select id
from t
group by id
order by min(weight),
id
/For example:
SQL> with merger as (
2 select 1 sno,100 winner_id,200 looser_id from dual union all
3 select 2,304,500 from dual union all
4 select 3,100,400 from dual union all
5 select 4,456,700 from dual union all
6 select 5,100,987 from dual
7 ),
8 t as (
9 select winner_id id,
10 1 weight
11 from merger
12 union all
13 select looser_id,
14 2 weight
15 from merger
16 )
17 select id
18 from t
19 group by id
20 order by min(weight),
21 id
22 /
ID
100
304
456
200
400
500
700
987
8 rows selected.
SQL> SY. -
Converting rows to columns using t-sql
Hi All,
I have a table with 3 columns, let say ID1 , ID2, Flag
My Source data looks like this..
ID1 ID2 Flag
1 1 0
1 2 0
1 3 0
2 7 0
2 8 1
2 9 0
4 5 0
Now My output should look like this..
ID1 Newcol1 NewFlag1 Newcol2 NewFlag2 Newcol3 NewFlag3
1 1 0
2 0 3
0
2 7 0
8 1 9
0
4 5 0
null null null null
Basically I want to convert rows to columns and to get above output I need t-SQL query.
Thanks in advance
RH
sqlYou can do it by this query:
declare @table table ( ID1 int, ID2 int, Flag int)
insert @table values ( 1,1,0 ),( 1,2,0 ),( 1,3,0 ),( 2,7,0 ),( 2,8,1 ),( 2,9,0 ),( 4,5,0 )
WITH cte1
AS ( SELECT Id1 ,
ROW_NUMBER() over (partition by ID1 order by ID1 ) as Sequence ,
ID2 ,
Flag
FROM @table
cte2
AS ( SELECT Id1 ,
ColumnTitle + LTRIM(RTRIM(STR(Sequence))) AS ColumnTitle ,
ColumnData
FROM cte1 UNPIVOT ( ColumnData FOR ColumnTitle IN ( [ID2], [Flag] ) ) AS UP
SELECT Id1 ,
[ID21] FirstID2 ,
[Flag1] FirstFlag ,
[ID22] SecondID2 ,
[Flag2] SecondFlag ,
[ID23] ThirdID2 ,
[Flag3] ThirdFlag
FROM cte2 PIVOT ( MAX(ColumnData) FOR ColumnTitle IN ( [ID21],
[Flag1],
[ID22],
[Flag2],
[ID23],
[Flag3] ) ) PV
If you want to know more detail, please visit my old article about this method:
T-SQL: PIVOT Ordered pair Columns
T-SQL e-book by TechNet Wiki Community
My Blog
My Articles -
How to put line break in the text
Hi guys,
This is a simple problem.i don't know how to concat a line break while creating a text.
I am looping through the results of a query and want to form the text using the results.
For each row of the resultset,I want to create a new line in the text i create.
I was wondering how to put a new line in the text.
I thought I can concat '\n' ,but it does not work.
the code snippet in the procedure is :
for c1_rec in c1 loop
vMsg := ' There are ' || c1_rec.total ||
' documents of type ' || c1_rec.doc_type || '\n' ;
end loop;
Please give the solution.
Thanks in advance.Thank you Mark.
I tried your suggestion.But line break is not working in email.
Here is how my code is
in procedure 1 ,i create the message String as :
for c1_rec in c1 loop
vMsg := vMsg || ' ' || today_str || ' - ' || c1_rec.total ||
' Total inbound documents from : ' || c1_rec.target_value || CHR(13)||CHR10) ;
dbms_output.put_line(' ' || vMsg);
end loop;
--here sending mail calling another procedure
sendmail( '[email protected]' ,'[email protected]' , 'Test Subject ' , vMsg );
In Procedure 2( i.e sendmail procedure )
i am preparing email server connection from and to adresses .Then i am preparing and sending message as
crlf VARCHAR2( 2 ):= CHR( 13 ) || CHR( 10 );
conn:= utl_smtp.open_connection( EmailServer, Port );
utl_smtp.helo( conn, EmailServer );
utl_smtp.mail( conn, SENDER);
utl_smtp.rcpt( conn, RECEIVER )
mesg:= 'Subject: ' || SUBJECT || crlf ||
'Date: '||TO_CHAR( SYSDATE, 'Dy, dd Mon yyyy hh24:mi:ss' )||
crlf ||
'From:'||SENDER|| crlf ||
'To: '||RECEIVER || crlf ||
'Content-Type: text/html; charset=ISO-8859-1' || crlf ||
'' || crlf || MESSAGE ;
utl_smtp.data( conn, mesg );
utl_smtp.quit( conn );
even now the mail we are getting is not having the line break.I am having line break in dbms output,but not in the mail.
Is there any mistake how I am sending the mail.Or is there any other way we can put line break in the text
Thank you. -
Please Help me!!!
I want to convert rows into columns ,-----
script:---
create table jobwork (vrno varchar2(11),job_str varchar2(1000));
VRNO JOB_STR
J101 J111,J112,J113,J114
J201 J211,J222,J223,J224,J225
J301 J311,J312
J401 J411,J422,J423,J425,JJ426,J427
I want output like :---
VRNO JOB_STR
J101 J111
J101 J112
J101 J113
J101 J114
J201 J211
J201 J222
J201 J223
J201 J224
J201 J225
and so on...........942425 wrote:
Please Help me!!!
I want to convert rows into columns ,-----Not according to what you posted below. You want to break out a comma separated list.
This wouldn't be required if the data was stored in a proper relational format (you should look to change the data model).
942425 wrote:
script:---
create table jobwork (vrno varchar2(11),job_str varchar2(1000));
VRNO JOB_STR
J101 J111,J112,J113,J114
J201 J211,J222,J223,J224,J225
J301 J311,J312
J401 J411,J422,J423,J425,JJ426,J427
I want output like :---
VRNO JOB_STR
J101 J111
J101 J112
J101 J113
J101 J114
J201 J211
J201 J222
J201 J223
J201 J224
J201 J225
and so on...........If we knew your Oracle version I could be more precise, but since I have no idea what version you are on...
https://www.google.com/#output=search&sclient=psy-ab&q=oracle+break+out+comma+separated+string&oq=oracle+break+out+comm&gs_l=hp.3.0.0i22i30.226.3329.0.4689.21.19.0.2.2.0.190.2042.10j9.19.0...0.0.0..1c.1.16.psy-ab.X1wge4Bavd8&pbx=1&bav=on.2,or.r_qf.&bvm=bv.47534661,d.cGE&fp=e8ac345f62c30ea5&biw=1850&bih=1083
Will give you the ability to figure out which techniques are applicable for your version.
Cheers, -
Hi.is it possible to add 2 columns and put it in the third calumn thru sqll
Hi.is it possible to add 2 columns and put it in the third calumn thru sqll
Hi i have 3 columns
callstart,duration and callrelease
In the extract i get values only for callstart and duration.
Is possible thru sqlldr to output the sum of callstart and duration into callrelease.May This Can Help You..
SQL> select * from table_a;
ID SCHEDULED MARK PRID
5 07-NOV-10 T05 7
6 18-SEP-10 T06 8
4 31-JAN-11 T02 2
1 18-JAN-11 T01 2
2 18-JAN-11 T02 10
3 18-JAN-11 T03 1
6 rows selected.
SQL> alter table table_a add mix varchar(50);
Table altered.
SQL> select * from table_a;
ID SCHEDULED MARK PRID MIX
5 07-NOV-10 T05 7
6 18-SEP-10 T06 8
4 31-JAN-11 T02 2
1 18-JAN-11 T01 2
2 18-JAN-11 T02 10
3 18-JAN-11 T03 1
6 rows selected.
SQL> update table_a
2 set mix=mark||to_char(id);
6 rows updated.
SQL> commit;
Commit complete.
SQL> select * from table_a;
ID SCHEDULED MARK PRID MIX
5 07-NOV-10 T05 7 T055
6 18-SEP-10 T06 8 T066
4 31-JAN-11 T02 2 T024
1 18-JAN-11 T01 2 T011
2 18-JAN-11 T02 10 T022
3 18-JAN-11 T03 1 T033
6 rows selected.
SQL> Regards
Umesh -
Converting Rows into Column in Oracle 10g
Hi All,
I m using Oracle Version 10.1.0.2.0 - Production
I have requirement to convert rows into column wise as per the following:
My Query is:
WITH t
AS ( SELECT 'A' AS x, 100 AS y FROM DUAL
UNION ALL
SELECT 'B',200 FROM DUAL
SELECT X, Y
FROM t;
X Y
A 100
B 200
My Requirement is
A B
100 200
So any one could help me that how I resolve this.
Regards,
PrasantaDear frank,
Thanks for your support,.
It's working fine for static cases.If the first column is dynamic then how come i will resolve it.
Example:
Create table mytab (ID_C Varchar2(15),Value_N Number);
Records Population into MyTab table is dynamic.
Insert into mytab values('HO',5000);
Insert Into mytab values('PG1',2400);
Insert Into mytab values('PG2',3000);
Insert Into mytab values('PG3',800);
Commit;
SQL> Select * From MyTab;
IDC_ ValueN_
HO 5000
PG1 2400
PG2 3000
PG3 800
Then My expected result will be as follows
HO PG1 PG2 PG3
5000 2400 3000 800
Thanks and Regards,
Prasanta -
Converting rows to columns using dynamic query.
I am trying to use the below code that I founnd on the web to conver rows to columns. the reason that I want to use dynamic query is that the number of rows are not know and changes.
declare
lv_sql varchar2(32767) := null ;
begin
lv_sql := 'SELECT Iplineno ';
for lv_rec in (SELECT distinct vendor from bidtabs where letting = '10021200' and call ='021')
loop
lv_sql := lv_sql
|| CHR(10)
|| ', MAX( DECODE( vendor, '
|| chr(39)
|| lv_rec.vendor
|| CHR(39)
|| ', bidprice, NULL ) ) as "'
|| lv_rec.vendor
|| '" ' ;
end loop;
lv_sql := lv_sql
|| CHR(10)
|| 'FROM bidtabs where letting = ''10021200'' and call = ''021'' and lineflag = ''L'' '
|| CHR(10)
|| 'GROUP BY iplineno ;' ;
here is the result
BIDPRICE CALL IPLINENO LETTING VENDOR
9,585 021 0010 10021200 C0104
1,000 021 0020 10021200 C0104
1,000 021 0030 10021200 C0104
17 021 0040 10021200 C0104
5 021 0050 10021200 C0104
11,420 021 0010 10021200 K0054
1,100 021 0020 10021200 K0054
1,100 021 0030 10021200 K0054
5 021 0040 10021200 K0054
3 021 0050 10021200 K0054
8,010 021 0010 10021200 V070
900 021 0020 10021200 V070
1,320 021 0030 10021200 V070
11 021 0040 10021200 V070
3 021 0050 10021200 V070
and here is the desired output
CALL IPLINENO LETTING C0104 K0054 V070
021 0010 10021200 9,585 11,420 8,010
021 0020 10021200 1,000 1,100 900
021 0030 10021200 1,000 1,100 1,320
021 0040 10021200 17 5 11
021 0050 10021200 5 3 3Here is the error message I am getting:
RA-06550: line 22, column 43:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
begin case declare end exception exit for goto if loop mod
null pragma raise return select update while with
<an identifier> <a double-quoted delimited-identifier>
<a bind variable> << close current delete fetch lock insert
open rollback savepoint set sql execute commit forall merge
pipe -
How to convert row into column
Hi All,
My oracle apps version is r12 and db is 10 and i am using Bi publisher version 10g.
Is it possible to convert row into column in Rtf template,
My Query is
SELECT distinct pvs.vendor_site_code,sum(aia.invoice_amount)
FROM ap_invoices_all aia, po_vendors po, po_vendor_sites_all pvs
WHERE aia.org_id = pvs.org_id
AND aia.vendor_id = po.vendor_id
AND aia.vendor_site_id = pvs.vendor_site_id
AND aia.org_id=204
group by pvs.vendor_site_code
And output is like this
Vendor sitecode Invoiceamt
EAM-ERS 79240
STAR GATE - PAY 3245902.31
UPS - HQ 10792040.9
Like this
So in template i need the output like this
Vendor sitecode EAM-ERS STAR GATE - PAY UPS - HQ
Invoiceamt 79240 3245902.31 10792040.9
I tried to achieve the output using sql query but by hardcoding only i have achieved it, so i have tried to convert directly in RTF template.
can any one tell me is it possible.
And if new project is added from the front end ie(now the query will produce 4 rows but now in template i have created only three columns)
Is it possible to add a new column dynamically.
Can any one please guide me and tell me is there any example.
Thanks & regards
SrikkanthTake a look at this post: http://blogs.oracle.com/roller-ui/bsc/spider.jsp?entry=MT%3aENTRY%3a5001
Thanks,
Bipuser -
How to convert rows into columns with decode function
Hi,
How to convert rows into columns with the help of decode function in oracle.
thanks and regards
P Prakashsay
col1 col2
1 10
2 20
3 30
then use
select col1,
sum(decode(col2,10,10)) "new1"
sum(decode(col2,20,20))"new2"
sum(decode(col2,30,30))"new3"
from table_name
group by col1;
we used sum u can use ny function if wont u have to give the column name i.e col2 name also
so i think u got it nw
regards -
CONVERT ROWS INTO COLUMNS IN INTERNAL TABLE
Hi Experts,
I want to convert rows into coloumns in final internal table.
How to do that one. Can any one help me its very urgent.
Regards,
PBS.hi,
Find the below code for changing rows into colums.
data: begin of itab1 occurs 0,
fld,
end of itab1.
data: begin of itab2 occurs 0,
fld1,
fld2,
fld3,
end of itab2.
itab1-fld = 1.
append itab1.
itab1-fld = 2.
append itab1.
itab1-fld = 3.
append itab1.
read table itab1 index 1.
if sy-subrc eq 0.
itab2-fld1 = itab1-fld.
endif.
read table itab1 index 2.
if sy-subrc eq 0.
itab2-fld2 = itab1-fld.
endif.
read table itab1 index 3.
if sy-subrc eq 0.
itab2-fld3 = itab1-fld.
endif.
append itab2.
loop at itab1.
write:/ itab1.
endloop.
loop at itab2.
write:/ itab2.
endloop.
refer the below link for further information
internal table rows to columns
in the final display list how can i change rows to columns and vice versa -
Convert rows into columns nad vice versa in 10g
how to convert rows into columns in 10g??
Qwerty wrote:
see below for rows to column case
SQL> WITH t as
2 (
3 SELECT 'US' test_string FROM DUAL UNION
4 SELECT 'AMERICA' FROM DUAL UNION
5 SELECT'HOLLYWOOD' FROM DUAL UNION
6 SELECT 'WASHINGTON' FROM DUAL
7 )
8 select ltrim (sys_connect_by_path(test_string,','),',') test_string
9 from (
10 SELECT row_number() over(order by test_string) rno, test_string
11 FROM t)
12 WHERE connect_by_isleaf = 1 and rownum=1
13 connect by rno = prior rno+1;
TEST_STRING
AMERICA,HOLLYWOOD,US,WASHINGTONI hope you can do it for column to rows now.That's not really rows to columns. That's rows to a column, which is more commonly called string aggregation.
Rows to columns (or pivot) is more like:
SQL> ed
Wrote file afiedt.buf
1 WITH t as
2 (
3 SELECT 'US' test_string FROM DUAL UNION
4 SELECT 'AMERICA' FROM DUAL UNION
5 SELECT'HOLLYWOOD' FROM DUAL UNION
6 SELECT 'WASHINGTON' FROM DUAL
7 )
8 --
9 select max(decode(rn,1,test_string)) as col_1
10 ,max(decode(rn,2,test_string)) as col_2
11 ,max(decode(rn,3,test_string)) as col_3
12 ,max(decode(rn,4,test_string)) as col_4
13* from (select test_string, row_number() over (order by test_string) as rn from t)
SQL> /
COL_1 COL_2 COL_3 COL_4
AMERICA HOLLYWOOD US WASHINGTON
SQL>And columns to rows (or unpivot) is like:
SQL> ed
Wrote file afiedt.buf
1 WITH t as
2 (
3 SELECT 'US' col_1, 'AMERICA' col_2, 'HOLLYWOOD' col_3, 'WASHINGTON' col_4 FROM DUAL
4 )
5 --
6 select col_1 as col from t union all
7 select col_2 from t union all
8 select col_3 from t union all
9* select col_4 from t
SQL> /
COL
US
AMERICA
HOLLYWOOD
WASHINGTONor...
SQL> ed
Wrote file afiedt.buf
1 WITH t as
2 (
3 SELECT 'US' col_1, 'AMERICA' col_2, 'HOLLYWOOD' col_3, 'WASHINGTON' col_4 FROM DUAL
4 )
5 --
6 select decode(rownum,1,col_1,2,col_2,3,col_3,4,col_4) as col
7* from t, (select * from dual connect by rownum <= 4)
SQL> /
COL
US
AMERICA
HOLLYWOOD
WASHINGTON
SQL> -
Select Statement - How do i convert rows to columns
Hi, i need your help please.
i have three options: A, B, C in table T_OPTIONS (not more and not less, it is always 3)
no i can assign articles to this option.
Article 1, 2, 3, 4
in the table it looks like this
ARTICLE_ID T_OPTIONS
1 A
1 B
2 C
3 A
3 C
But now i want to have a select statement which convert rows to columns, it has to look like this
ARTICLE A B C
1 x x
2 x
3 x x
Can you help me!?
Edited by: Dila on 02.08.2012 01:52
Edited by: Dila on 02.08.2012 01:53Dila wrote:
Hi, i need your help please.
i have three options: A, B, C in table T_OPTIONS (not more and not less, it is always 3)
no i can assign articles to this option.
Article 1, 2, 3, 4
in the table it looks like this
ARTICLE_ID T_OPTIONS
1 A
1 B
2 C
3 A
3 C
But now i want to have a select statement which convert rows to columns, it has to look like this
ARTICLE A B C
1 x x
2 x
3 x x
Can you help me!?
Edited by: Dila on 02.08.2012 01:52
Edited by: Dila on 02.08.2012 01:53Read {message:id=9360002} and {message:id=9360005}
SQL> ed
Wrote file afiedt.buf
1 with sample_data as
2 (
3 select 1 ARTICLE_ID,'A' T_OPTIONS from dual union all
4 select 1, 'B' from dual union all
5 select 2, 'C' from dual union all
6 select 3, 'A' from dual union all
7 select 3, 'C' from dual
8 )
9 select article_id,
10 decode(sum(case
11 when t_options = 'A' then 1
12 else 0
13 end), 0, null,
14 'X') A,
15 decode(sum(case
16 when t_options = 'B' then 1
17 else 0
18 end), 0, null,
19 'X') B,
20 decode(sum(case
21 when t_options = 'C' then 1
22 else 0
23 end), 0, null,
24 'X') C
25 from sample_data
26* group by article_id
SQL> /
ARTICLE_ID A B C
1 X X
2 X
3 X X -
How to convert rows to columns in sql server 2008
How to convert rows to columns in sql server 2008 using the GROUP BY function? (only one query allowed)
Lookup the Pivot transformation. From BOL:
The Pivot transformation makes a normalized data set into a less normalized
but more compact version by pivoting the input data on a column value. For
example, a normalized Orders data set that lists customer name, product, and quantity purchased typically has multiple rows for any customer who purchased multiple products, with each row for that customer showing order
details for a different product. By pivoting the data set on the product column, the Pivot transformation can output a data set with a
single row per customer. That single row lists all the purchases by the customer, with the product names shown as column names, and the quantity shown as a value in the product column. Because not every customer purchases every product, many columns may contain
null values.
When a dataset is pivoted, input columns perform different roles in the pivoting process. A column can participate in the following ways:
The column is passed through unchanged to the output. Because many input rows
can result only in one output row, the transformation copies only the first
input value for the column.
The column acts as the key or part of the key that identifies a set of
records.
The column defines the pivot. The values in this column are associated with
columns in the pivoted dataset.
The column contains values that are placed in the columns that the pivot
creates.
Paul
Maybe you are looking for
-
Setting default sound card to card 0
Hi, After following Arch Wiki for configuring Alsa I added the following to my /etc/asound.conf: efaults.pcm.card 0 defaults.pcm.device 0 defaults.ctl.card 0 This works on my current session. However, sometimes when I reboot my computer, my primary s
-
Mac does not connect automatically to known Networks
hi, recently my Macbook has stoped reconnecting to my wifi when I open the lid and I have to do it manually. any idea to solves this? thks regards
-
Configuring oracle 8i for multiple language support?
We are in discovery for a new web site that will need to support many languages. The initial phase is for English and some European languages like swedish and french but plans are to include multi-byte languages like japanease in the future. What are
-
Transfer apps/games to sd card
Why cant sony just allow this feature again. Seems pointless to market it as an hd gaming smartphone if you are limited to using the 11GB storage for installing huge hd games right? Plus it would also solve the insufficient storage problem. A 33MB up
-
Maintaining Number Group for Internal Challan
hi experts, while configuring the J_1IEWTNUMGR_1 table views and entering the number groups for internal challan numbers Ewt india am getting an error " Entry BP01 BP10 does not exist in SEC CODE check your entry" BP01 is the company code BP10 is the