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 2000 Forums
 SQL Server Development (2000)
 Transposition Query

Author  Topic 

timgaunt
Posting Yak Master

115 Posts

Posted - 2007-02-23 : 11:19:56
Hi,

There was a question that came up today on one of the lists I'm on whereby the user wanted to transpose:
id | team | company | name | discipline

into:
id | team | company | swimming | running | cycling

Is this solution that I came up with overly inefficient?

TIA

Tim

DECLARE @Temp Table(
id int,
team int,
company nvarchar(10),
name nvarchar(10),
discipline nvarchar(10)
)

INSERT INTO @Temp
SELECT 1, 1, 'Company 1', 'User 1', 'S' UNION ALL
SELECT 2, 1, 'Company 1', 'User 2', 'R' UNION ALL
SELECT 3, 1, 'Company 1', 'User 3', 'C' UNION ALL
SELECT 4, 2, 'Company 2', 'User 4', 'R' UNION ALL
SELECT 5, 2, 'Company 2', 'User 5', 'S' UNION ALL
SELECT 6, 2, 'Company 2', 'User 6', 'C' UNION ALL
SELECT 7, 3, 'Company 3', 'User 7', 'C' UNION ALL
SELECT 8, 3, 'Company 3', 'User 8', 'R' UNION ALL
SELECT 9, 3, 'Company 3', 'User 9', 'S'

SELECT DISTINCT
team,
company,
(SELECT TOP 1 [Name] FROM @Temp s WHERE s.discipline = 'S' AND s.team = t.team) As Swimmer,
(SELECT TOP 1 [Name] FROM @Temp r WHERE r.discipline = 'R' AND r.team = t.team) As Runner,
(SELECT TOP 1 [Name] FROM @Temp c WHERE c.discipline = 'C' AND c.team = t.team) As Cyclist

FROM
@Temp t

GROUP BY
team,
company,
Name,
discipline


----------------------------
I've finally started blogging (all be it badly!)

Check it out:
http://blogs.thesitedoctor.co.uk/tim/

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2007-02-23 : 20:34:11
[code]
select team, company,
max(case when discipline = 'S' then [name] end) as Swimmer,
max(case when discipline = 'R' then [name] end) as Runner,
max(case when discipline = 'C' then [name] end) as Cyclist
from @Temp
group by team, company
[/code]


KH

Go to Top of Page

timgaunt
Posting Yak Master

115 Posts

Posted - 2007-02-26 : 01:33:47
Yeah Thanks KH I realised that over the weekend, sometimes I'm half asleep ;)

Tim

----------------------------
I've finally started blogging (all be it badly!)

Check it out:
http://blogs.thesitedoctor.co.uk/tim/
Go to Top of Page
   

- Advertisement -