Click here to Skip to main content
15,896,201 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Scenario:
Name	  Comp	     DOJ
Kris	  Aa	     2010
Naik	  Bb	     2013
kris	  Cc	     2011
Nana	  Dd	     2014

Output: Want each individual person who joined in their first comp i.e if there were more than 1 lacks records then who u build logic.

Above example output is:
Kris	2010	2011
Naik	2013	 
Nana	2014

Build the logic for the above result.
Posted
Updated 25-Jun-14 9:47am
v4
Comments
Sergey Alexandrovich Kryukov 25-Jun-14 10:02am    
Not clear, not a question.
—SA
Maciej Los 25-Jun-14 15:48pm    
Not clear!

1 solution

Not sure what you want, but you can use Pivot[^] table. Have a look at sample code:
SQL
DECLARE @tmp TABLE([Name] VARCHAR(30), Comp VARCHAR(30), DOJ INT)

INSERT INTO @tmp ([Name], Comp, DOJ)
VALUES('Kris', 'Aa', 2010),
('Naik', 'Bb', 2013),
('Kris', 'Cc', 2011),
('Nana', 'Dd', 2014)


SELECT [Name], [1], [2]
FROM (
    SELECT ROW_NUMBER() OVER(PARTITION BY [Name] ORDER BY [Name], DOJ) AS RowID, [Name], DOJ
    FROM @tmp
) AS DT
PIVOT (MAX(DOJ) FOR [RowID] IN([1], [2])) AS PT


Result:
Name    1       2
Kris	2010	2011
Naik	2013	NULL
Nana	2014	NULL


More:
Simple Way To Use Pivot In SQL Query[^]
Pivots with Dynamic Columns in SQL Server 2005[^]
 
Share this answer
 
Comments
Jörgen Andersson 25-Jun-14 17:20pm    
+5
Maciej Los 26-Jun-14 16:41pm    
Thank you, Jörgen ;)
P.S. I hadn't get notification about your comment.

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