I have a table look like this:
P_ID Lang
1001 EN
1001 German
Expecting result:
P_ID Lang1 Lang2
1001 EN German
I have a table look like this:
P_ID Lang
1001 EN
1001 German
Expecting result:
P_ID Lang1 Lang2
1001 EN German
I just had to do a PIVOT like this, so here is my code modified for your situation:
SELECT * FROM
(
SELECT P_ID,
Lang,
NumberedLang = 'Lang' + CAST(ROW_NUMBER() OVER
(PARTITION BY P_ID ORDER BY Lang) AS NVARCHAR(100))
FROM YourTableName
) AS OrderLangs
PIVOT (MAX(Lang) FOR NumberedLang IN (Lang1, Lang2)) AS PivotedLangs
Here is an SQL Fiddle to show you that it works.
If you don't want to specify all of the different NumberedLang
values then you will have to use 'dynamic' pivots where you do all of the code in text based SQL. They can be quite inefficient though due to no query plan available.
It's a bit ugly, but you can do something like this:
select p_id
, max( case when langNum=1 then lang else null end ) as Lang1
, max( case when langNum=2 then lang else null end ) as Lang2
, max( case when langNum=3 then lang else null end ) as Lang3
, max( case when langNum=4 then lang else null end ) as Lang4
, max( case when langNum=5 then lang else null end ) as Lang5
-- ...
from (
select p_id
, lang
-- Get a number for each row, starting from 1 for each p_id:
, row_number() over ( partition by p_id order by lang ) as LangNum
from theTable
) as x
group by p_id