0

i have the sql code that returns the result

Set1   Value
A       A1      
A       A2
A       A3
A       A4

How do i display the result like this

Set1    Value1      Value2       Value3      Value4
A           A1        A2           A3          A4

Thanks

Chandu
  • 81,493
  • 19
  • 133
  • 134
JOhn
  • 9
  • 1
  • i was wondering exactly the same thing in the morning. :) – Phphelp Jul 06 '11 at 03:19
  • You may be able to achieve this with Common Table Expression. I am not sure though. What would you need this behavior for? – jworrin Jul 06 '11 at 03:20
  • 1
    Please tag and/or specify the version of SQL Server you are using. In 2005+ you can use PIVOT but there's little sense coding a solution if it's not going to be valid. – Aaron Bertrand Jul 06 '11 at 03:43

2 Answers2

2

take a look at this

SQL Server: Examples of PIVOTing String data

Community
  • 1
  • 1
Binil
  • 6,445
  • 3
  • 30
  • 40
0

Following would do the trick. Using ROW_NUMBER allows for values other than A1-A4

SQL Statement

SELECT  [Set1] = Set1
        , [Value1] = MIN(CASE WHEN rn = 1 THEN Value END)
        , [Value2] = MIN(CASE WHEN rn = 2 THEN Value END)
        , [Value3] = MIN(CASE WHEN rn = 3 THEN Value END)
        , [Value4] = MIN(CASE WHEN rn = 4 THEN Value END)
FROM    (       
            SELECT  Set1
                    , Value
                    , rn = ROW_NUMBER() OVER (PARTITION BY Set1 ORDER BY Value)
            FROM    AResult
        ) q
GROUP BY
        Set1        
Lieven Keersmaekers
  • 57,207
  • 13
  • 112
  • 146