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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Table Transpose help

Author  Topic 

alwaysram
Starting Member

5 Posts

Posted - 2008-10-02 : 11:07:12
Hi
I need some SQL experts help. I have a table in the following format, this gets updated through a ftp csv feed using SSIS.

Location Variable Col1 Col2 Col3 Col4 Col5
London DateTime 10Feb3AM 10Feb9AM 10Feb3PM 10Feb9PM 11Feb3AM
London Temperature 10 11 12 12 8 8
London Weather FA FA SH FA FA CL
London MaxTemp 11 13 14 14 11 10
London MinTemp 7 10 10 8 5 6
This is not in a helpful format. I want a query which returns the output in the following format. with given column names. I though Pivot command may help, but its not.

Location DateTime Temperature Weather MaxTemp MinTemp
London 10Feb3AM 10 FA 11 7
London 10Feb9AM 11 FA 13 10
London 10Feb3PM 12 SH 14 10
London 10Feb9PM 8 FA 11 5
London 11Feb3AM 8 CL 10 6


Your help is much appreciated
Ramesh

RyanRandall
Master Smack Fu Yak Hacker

1074 Posts

Posted - 2008-10-02 : 13:56:48

declare @t table (Location varchar(20), Variable varchar(20), Col1 varchar(20), Col2 varchar(20), Col3 varchar(20), Col4 varchar(20), Col5 varchar(20))
insert @t
select 'London', 'DateTime', '10Feb3AM', '10Feb9AM', '10Feb3PM', '10Feb9PM', '11Feb3AM'
union all select 'London', 'Temperature', '10', '11', '12', '12', '8'
union all select 'London', 'Weather', 'FA', 'FA', 'SH', 'FA', 'FA'
union all select 'London', 'MaxTemp', '11', '13', '14', '14', '11'
union all select 'London', 'MinTemp', '7', '10', '10', '8', '5'

select id,
max(case when Variable = 'DateTime' then Col else '' end) as 'DateTime',
max(case when Variable = 'Temperature' then Col else '' end) as 'Temperature',
max(case when Variable = 'Weather' then Col else '' end) as 'Weather',
max(case when Variable = 'MaxTemp' then Col else '' end) as 'MaxTemp',
max(case when Variable = 'MinTemp' then Col else '' end) as 'MinTemp'
from (
select 1 as id, Location, Variable, Col1 as Col from @t
union all select 2, Location, Variable, Col2 from @t
union all select 3, Location, Variable, Col3 from @t
union all select 4, Location, Variable, Col4 from @t
union all select 5, Location, Variable, Col5 from @t) a
group by id


Ryan Randall
Solutions are easy. Understanding the problem, now, that's the hard part.
Go to Top of Page

alwaysram
Starting Member

5 Posts

Posted - 2008-10-13 : 08:13:24
Excellent Ryan. Clever solution and I fixed it. Thanks you very much for your time and help. I really appreciate you.
Go to Top of Page
   

- Advertisement -