0

I have a table like this:

name     orderid
bambino  4,5,6,7,8

How can we separate values in orderid column into different columns like in example below?

name     order1 order2 order3 order4 order5
bambino  4      5      6      7      8
Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
Sadda-shutu
  • 1,309
  • 2
  • 18
  • 42

4 Answers4

0

If you have a fixed amount of values in your orderid column, this question could maybe help you:

How to split a comma seperated value to columns

Community
  • 1
  • 1
Challex
  • 42
  • 6
0

Some tricks with xml and then pivoting:

DECLARE @t TABLE
    (
      name VARCHAR(20) ,
      orderid VARCHAR(20)
    )

INSERT  INTO @t
VALUES  ( 'chao', '1,2,3' ),
        ( 'bambino', '4,5,6,7,8' );
WITH    cte
          AS ( SELECT   name ,
                        Split.a.value('.', 'VARCHAR(100)') AS orderid ,
                        ROW_NUMBER() OVER ( PARTITION BY name ORDER BY ( SELECT
                                                              NULL
                                                              ) ) rn
               FROM     ( SELECT    name ,
                                    CAST ('<M>' + REPLACE(orderid, ',',
                                                          '</M><M>') + '</M>' AS XML) AS orderid
                          FROM      @t
                        ) AS A
                        CROSS APPLY orderid.nodes('/M') AS Split ( a )
             )
    SELECT  name ,
            [1] AS order1 ,
            [2] AS order2 ,
            [3] AS order3 ,
            [4] AS order4 ,
            [5] AS order5 ,
            [6] AS order6 ,
            [7] AS order7 ,
            [8] AS order8 ,
            [9] AS order9 ,
            [10] AS order10
    FROM    cte PIVOT( MAX(orderid) FOR rn IN ( [1], [2], [3], [4], [5], [6],
                                                [7], [8], [9], [10] ) ) p

Output:

name    order1  order2  order3  order4  order5  order6  order7  order8  order9  order10
bambino 4       5       6       7       8       NULL    NULL    NULL    NULL    NULL
chao    1       2       3       NULL    NULL    NULL    NULL    NULL    NULL    NULL
Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
0

Here is a really good webpage on how you can split an comma separated string into rows. There are many different approaches so pick a way that suits your needs. (Eg CLR will be faster than a XML 'hack', but this might not be a concern.)

Once you've got your data in rows you can then use PIVOT to turn it into columns. You might have to do this in dynamic SQL if you don't know how many columns you're going to have.

BJury
  • 2,526
  • 3
  • 16
  • 27
0

Most simplest and dynamic query for this, This query won't mind if you have million orders in orderid column

declare @name as nvarchar(50), @orderid as nvarchar(50), @dorders as nvarchar(max)='',@count as int = 1
select @name=name, @orderid=orderid from abc -- add here where clause to select particular row
select @dorders = @dorders + splitdata + ' as [Order'+convert(nvarchar(10),@count)+'],', @count = @count + 1 from fnsplitstring(@orderid,',')
set @dorders = SUBSTRING(@dorders,0,len(@dorders))
declare @Dsql as nvarchar(max) = 'select '''+@name+''' as name, '+@dorders
exec (@Dsql)

For your reference

enter image description here

Ohh.. And add this function, its helpful anyways ..

CREATE FUNCTION [dbo].[fnSplitString] 
( 
    @string NVARCHAR(MAX), 
    @delimiter CHAR(1) 
) 
RETURNS @output TABLE(splitdata NVARCHAR(MAX) 
) 
BEGIN 
    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1

        INSERT INTO @output (splitdata)  
        VALUES(SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)

    END 
    RETURN 
END
ThePravinDeshmukh
  • 1,823
  • 12
  • 21
  • What happens when you tables has 2 or more rows? – ughai Jun 11 '15 at 09:26
  • **side note:** If you are going to use and recommend a sql based splitter, `DelimitedSplit8K`, created by Jeff Moden is the defacto. You can read more about it [here](http://www.sqlservercentral.com/articles/Tally+Table/72993/) and its performance comparison [here](http://sqlperformance.com/2012/07/t-sql-queries/split-strings). – ughai Jun 11 '15 at 09:29
  • OP here asked for single row named `bambino`, if he adds to the question, i will have to change the query – ThePravinDeshmukh Jun 11 '15 at 09:36
  • OP mentioned a table with sample data as `bambino`. Are you going to assume that the table will always have only a single row? – ughai Jun 11 '15 at 09:39
  • I'm assuming he is fetching one row at a time as a result set (as he shown) And he can choose which row by adding where clause where i'm assigning variable values (i.e., `@name, @orderid`). I've added comment to support my argument – ThePravinDeshmukh Jun 11 '15 at 09:42
  • thanks for reply @PravinDeshmukh let me try and come back to u – Sadda-shutu Jun 11 '15 at 10:46