Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have table which gives records as below
Select * From EMP
EMPID  VehicalID
1	AB-1
1	CD-1
1	DE-1
2	XY-1
2       PQ-2
---================================================================================---
I want output like this 
EPID              Veh1             Veh2             veh3
1                 AB-1             CD-1             DE-1
2                 XY-1             PQ-2
Posted
Updated 9-May-13 21:23pm
v3
Comments
gvprabu 10-May-13 3:27am    
How many Vehicle IDs are there for single Emp ID? then only u can frame the Output.
koolprasad2003 10-May-13 3:31am    
Basically Vehicle ID is dummy column name you can keep what ever you want. it's not mandatory to take veh1,veh2 you can take like col1,col2 ..
gvprabu 10-May-13 3:46am    
Yes that is not a problem, Maximum how many vehicles will be there for each employees...? Bcos we can't put simple query for this. we can do using SUB Query with ROW_NUMBER() Function
RelicV 10-May-13 3:48am    
Have a look at PIVOT option for a solution. That helps a lot
gvprabu 10-May-13 3:57am    
mmm okie

1 solution

[EDIT #1]
There is not possible to achieve that using pivot(s)[^], because aggregate function(s)[^] can be used only on numeric data.
[EDIT]

Try this:
SQL
DECLARE @emp TABLE(EMPID INT, VehicalID NVARCHAR(30))

INSERT INTO @emp (EMPID, VehicalID)
VALUES(1, 'AB-1')
INSERT INTO @emp (EMPID, VehicalID)
VALUES(1, 'CD-1')
INSERT INTO @emp (EMPID, VehicalID)
VALUES(1, 'DE-1')
INSERT INTO @emp (EMPID, VehicalID)
VALUES(2, 'XY-1')
INSERT INTO @emp (EMPID, VehicalID)
VALUES(2, 'PQ-2')

DECLARE @tmp TABLE (CID INT IDENTITY(1,1), EMPID INT, VehNo INT, VehicalID NVARCHAR(30))

INSERT INTO @tmp (EMPID, VehNo, VehicalID)
SELECT EMPID, ROW_NUMBER() OVER(PARTITION BY EMPID ORDER BY VehicalID) AS VehNo, VehicalID
FROM @emp

SELECT DISTINCT total.EMPID, t1.VehicalID AS Veh1, t2.VehicalID AS Veh2, t3.VehicalID AS Veh3
FROM @tmp AS total
    LEFT JOIN @tmp AS t1 ON total.EMPID = t1.EMPID AND t1.VehNo = 1
    LEFT JOIN @tmp AS t2 ON total.EMPID = t2.EMPID AND t2.VehNo = 2
    LEFT JOIN @tmp AS t3 ON total.EMPID = t3.EMPID AND t3.VehNo = 3


Returns:
EMPID   Veh1    Veh2    Veh3
1	AB-1	CD-1	DE-1
2	PQ-2	XY-1	NULL
 
Share this answer
 
v2
Comments
gvprabu 10-May-13 7:06am    
Great work... But he asked PIVOT Concept for this.
If data is changed again we have to change our Query right.
Maciej Los 10-May-13 7:11am    
Yes, we need to change query when data have been changed.
It's not possible to achieve that using pivot(s), because of no aggregation functions on text field (column).
gvprabu 10-May-13 7:15am    
nice my 5+ :-)
Maciej Los 10-May-13 7:17am    
Thank you ;)

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