Skip to content
Advertisement

select Unique row value in different column value in SQL

I have below table in SQL database with column ‘name’ has same value and column ‘Item’ has different values.

table :

Name Item
A Good
A Better
A Best

I would like achieve below result as output.

Result:

Name Item 1 Item 2 Item 3
A Good Better Best

Advertisement

Answer

Pivoting can done using an aggregated conditional case expression.

Your data is missing any column to provide explicit ordering to determin which row belongs in which column, which you may wish to address in your actual implementation, the ordering here is arbitrary:

select name,
    Max(case when col=1 then item end) Item1,
    Max(case when col=2 then item end) Item2,
    Max(case when col=3 then item end) Item3
from (
    select 
       name, 
       item, 
       Row_Number() over(partition by name order by name) col
    from t
)t
group by name
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement