SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 pivot table with string values?
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

skwash
Starting Member

USA
2 Posts

Posted - 07/17/2009 :  17:17:44  Show Profile  Reply with Quote
Would it be possible to create a pivot table using non-aggregate data?

Source table would look like:

ID Type Value
---------------------
1 Name Sam
1 Sex M
1 Phone 123
2 Name Sally
2 Sex F
3 Name Pat
4 Name Tom
4 Phone 456


Result would look like this:

ID Name Sex Phone
---------------------------
1 Sam M 123
2 Sally F Null
3 Pat Null Null
4 Tom Null 456


Does that make sense? I am open to doing the "pivot table" sort of action in Excel or even installing reporting services if I can get it at all.

Thanks,
Josh

SwePeso
Patron Saint of Lost Yaks

Sweden
30281 Posts

Posted - 07/17/2009 :  17:30:19  Show Profile  Visit SwePeso's Homepage  Reply with Quote
Yes, you can, but it will be awful slow compared to the PIVOT function.



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page

skwash
Starting Member

USA
2 Posts

Posted - 07/17/2009 :  17:55:46  Show Profile  Reply with Quote
What would you recommend? PIVOT requires aggregate functions correct?

The only way can think of doing it is through a big nasty dynamic sql statement.
Go to Top of Page

khtan
In (Som, Ni, Yak)

Singapore
17681 Posts

Posted - 07/18/2009 :  00:30:02  Show Profile  Reply with Quote

declare @sample table
(
	ID 	int,
	Type 	varchar(10),
	Value	varchar(10)
)
insert into @sample
select	1, 'Name',  'Sam'	union all
select	1, 'Sex',   'M'		union all
select	1, 'Phone', '123'	union all
select	2, 'Name',  'Sally'	union all
select	2, 'Sex',   'F'		union all
select	3, 'Name',  'Pat'	union all
select	4, 'Name',  'Tom'	union all
select	4, 'Phone', '456'

select	*
from	@sample s
	pivot
	(
		max(Value)
		for Type in ([Name], [Sex], [Phone])
	) p



KH
Time is always against us

Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52325 Posts

Posted - 07/18/2009 :  02:10:45  Show Profile  Reply with Quote
or simply do

SELECT ID,
MAX(CASE WHEN Type='Name' THEN Value ELSE NULL END) AS [Name],
MAX(CASE WHEN Type='Sex' THEN Value ELSE NULL END) AS [Sex],
MAX(CASE WHEN Type='Phone' THEN Value ELSE NULL END) AS [Phone]
FROM Table
GROUP BY ID
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000