Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to change the output with a dynamic T-SQL pivo

Author  Topic 

jensej
Starting Member

1 Post

Posted - 2015-04-02 : 07:55:57
This is my table.

CREATE TABLE tpivot
([col1] varchar(80), [col2] varchar(80), [col3] varchar(80), [col4] varchar(80), [col5] varchar(80))
;

INSERT INTO tpivot
([col1], [col2], [col3], [col4], [col5])
VALUES
('Datum', 'EC', 'Mastercard', 'Postfinance', 'VISA'),
('01.12.2014', '-204.9', '-88', '0', '-19'),
('02.12.2014', '-352.9', '0', '79.9', '-20'),
('03.12.2014', '-105', '-182', '0', '-436'),
('04.12.2014', '-371', '-122,9', '-751', '-343')

;



My goal is to turn the table so that the output look like this.

col1 col2 col3 col4 col5
Datum 01.12.2014 02.12.2014 03.12.2014 04.12.2014
EC -204.9 -352.9 -105 -371
Mastercard -88 0 -182 -112.9
Postfinance 0 -79.9 0 -751
VISA -19 -20 -436 -346

I need to have a dynamic pivot since i import the table from a csv that could have different amount of columns each time.

Can someone help me? I can't even get a static pivot to work :(

Thanks

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2015-04-02 : 09:02:28
Good example here of both static and dynamic transpose queries:

http://stackoverflow.com/questions/13372276/simple-way-to-transpose-columns-and-rows-in-sql
Go to Top of Page
   

- Advertisement -