Sql-server – How to get the row as column and one of the column as rows under the first column data

pivotsql serversql-server-2008-r2

I have table like below:

Tname         Scode
-----         -----
SVC           code1
SVC           code2
SVC           code3
AKV           code1
AKV           code12
AKV           code3
AKS           code3
AKS           code2
AKS           code1

I would want a result like below:

SVC      AKV         AKS
----     -----       ----
code1    code1       code3
code2    code12      code2
code3    code3       code1

Best Answer

You can try this. I think it's usefull, and will fix the problem if you have more codes in a column, I'm just trying to not select the row_number column.

SELECT *
FROM 
    (SELECT 
         Tname,scode,
         rn = ROW_NUMBER() OVER (PARTITION BY Tname ORDER BY Scode) 
     FROM teste_1) AS src
PIVOT (
  MIN(scode)
  FOR Tname IN ([SVC],[AKV],[AKS])
) AS pvt


| rn | SVC   | AKV    | AKS   | 
|----|-------|--------|-------|
| 1  | bola  | code1  | code1 |   
| 2  | code1 | code12 | code2 |   
| 3  | code2 | code3  | code3 |   
| 4  | code3 | NULL   | NULL  |