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)
 Using Pivot without aggreage fuction

Author  Topic 

angelcol
Starting Member

1 Post

Posted - 2009-06-30 : 13:20:21
I have a table like

Col1 Col2
A Peter
B Nelson
C USA
D 29
A Mary
B Kumar
C USA
d 25

I am trying to come up with something like this

Col1 Col2 Col3 Col4
Peter Nelson USA 29
Mary Kumar USA 25

I thought by using PIVOT I could do it, but since I do not need to use an aggregrate fuction.... I am not able to make it work without an aggregate function.

Any thought and help will be very welcome.

Thanks

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-06-30 : 13:30:33
do you have any other unique valued column in your table to determine the order?
Go to Top of Page

bklr
Master Smack Fu Yak Hacker

1693 Posts

Posted - 2009-07-01 : 06:23:30
try this by dynamic cross tab with out using aggregate functions

declare @i table (Col1 varchar(32),Col2 varchar(32))
insert into @i SELECT
'A','Peter' union all SELECT
'B','Nelson' union all SELECT
'C','USA' union all SELECT
'D','29' union all SELECT
'A','Mary' union all SELECT
'B','Kumar' union all SELECT
'C','USA' union all SELECT
'd','25'

DROP TABLE #temp
DROP TABLE #temp1

SELECT ROW_NUMBER() OVER(PARTITION BY COL1 ORDER BY col1) AS rid,* INTO #temp FROM @i

SELECT ROW_NUMBER()over(PARTITION BY rid ORDER BY col1,col2,col3,col4) AS id,* INTO #temp1 FROM
(SELECT t.rid,
CASE WHEN t.col1 = 'a' THEN t.col2
WHEN t.col1 = 'a' THEN t.col2 END col1,
CASE WHEN t1.col1 = 'b' THEN t1.col2
WHEN t1.col1 = 'b' THEN t1.col2 END col2,
CASE WHEN t2.col1 = 'c' THEN t2.col2
WHEN t2.col1 = 'c' THEN t2.col2 END col3,
CASE WHEN t3.col1 = 'd' THEN t3.col2
WHEN t3.col1 = 'd' THEN t3.col2 END col4
FROM #temp t
LEFT JOIN #temp t1 ON t1.rid = t.rid
LEFT JOIN #temp t2 ON t2.rid = t.rid
LEFT JOIN #temp t3 ON t3.rid = t.rid )s

DECLARE @maxid INT
SELECT @maxid = id FROM #temp1
SELECT col1,col2,col3,col4 FROM #temp1 where id = @maxid
Go to Top of Page
   

- Advertisement -