Click here to Skip to main content
15,890,845 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear Friends,

I have table in below mentioned format.
SQL
OWNER	VECH	VECH NO
SIVA	BUS	11
SIVA	BUS	22
SIVA	BUS	33
SIVA	CAR	44
SIVA	CAR	55
SIVA	CAR	66
SIVA	VAN	77
SIVA	VAN	88
SIVA	VAN	99


But I have the result to be displayed as
SQL
OWNER	BUS NO	CAR NO	VAN NO
SIVA	11	44	77
SIVA	22	55	88
SIVA	33	66	99


When I try using
Case when and MAX
function, it gives me only one row. Can any guide me on this.
Posted
Updated 10-Dec-13 18:57pm
v2

It should be something similar to this query:
SQL
DECLARE @tmp TABLE (OWNER VARCHAR(30), VECH VARCHAR(30), [VECH NO] INT)

INSERT INTO @tmp (OWNER, VECH, [VECH NO])
VALUES('SIVA', 'BUS', 11),
('SIVA', 'BUS', 22),
('SIVA', 'BUS', 33),
('SIVA', 'CAR', 44),
('SIVA', 'CAR', 55),
('SIVA', 'CAR', 66),
('SIVA', 'VAN', 77),
('SIVA', 'VAN', 88),
('SIVA', 'VAN', 99)


SELECT RowNo, OWNER, [BUS], [CAR], [VAN]
FROM (
   SELECT ROW_NUMBER() OVER (PARTITION BY VECH ORDER BY [VECH NO]) AS RowNo, OWNER, VECH, [VECH NO]
   FROM @tmp
) AS DT
PIVOT (MAX([Vech No]) FOR VECH IN ([BUS], [CAR], [VAN])) AS PT


If there is more than 3 destination columns, you need to use dynamic pivot[^] ;)

Result:
1	SIVA	11	44	77
2	SIVA	22	55	88
3	SIVA	33	66	99
 
Share this answer
 
v2
Comments
Arunprasath Natarajan 11-Dec-13 22:06pm    
I have tried the same but it gives me only max value as result.
Eg - Bus - 33, Car - 66 etc. (I need Bus no. 11 and 22 also)
Maciej Los 12-Dec-13 1:59am    
See my answer now ;)
Arunprasath Natarajan 12-Dec-13 8:33am    
Tan q. Row_Number() does not strikes my mind.
Maciej Los 12-Dec-13 9:14am    
;)
You can achieve this using the PIVOT function. Check this for examples: http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx[^]

That said, your data doesn't really indicate how you would actually have the car, bus and van numbers linked... there must be more to it.

If you have a fixed number of things, and don't feel like pivoting them, you could also achieve it using views, or subqueries... the options are endless!! (Well, maybe not endless...)
 
Share this answer
 
Hi Please take a look at this link,
http://blog.sqlauthority.com/2008/05/22/sql-server-pivot-table-example/[^]

This will give you idea about how to creating pivot table in sql server.

I am sure this will 100% solve your problem
 
Share this answer
 
Use PIVOT - UNPIVOT

Using PIVOT and UNPIVOT[^]
Pivoting data in SQL Server[^](Alternate ways)
 
Share this answer
 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900