split 1 column into 3 columns:

  • Hi Everyone,

    How can I break Column C :

    A - B - C - D

    1 - 61 - 1:00 -5/10/2011 2:00

    1 - 61 - 2:00- 5/10/2011 2:00

    1 - 61 - 3:00- 5/10/2011 2:00

    2 - 61 - 2:00- 5/10/2011 4:00

    2 - 61 - 3:00- 5/10/2011 4:00

    2 - 61 - 4:00- 5/10/2011 4:00

    INTO this:

    A - B - C1 -c2 -c3 - D

    1 - 61 - 1:00 -2:00- 3:00 - 5/10/2011 2:00

    2 - 61 - 2:00 -3:00- 4:00 - 5/10/2011 4:00

    Thanks for your help.

  • Will all A B combination have only 3 rows each ?

  • For your sample data:

    declare @testtable table

    ( A int, B int, C time , D datetime)

    insert into @testtable values

    (1 , 61 , '1:00' ,'5/10/2011 2:00')

    ,(1 , 61 , '2:00', '5/10/2011 2:00')

    ,(1 , 61 , '3:00', '5/10/2011 2:00')

    ,(2 , 61 , '2:00', '5/10/2011 4:00')

    ,(2 , 61 , '3:00', '5/10/2011 4:00')

    ,(2 , 61 , '4:00', '5/10/2011 4:00')

    ; WITH CTE AS

    (

    SELECT A , B , c , D ,

    RN = ROW_NUMBER() OVER( PARTITION BY A , B , D ORDER BY C )

    FROM @testtable

    )

    SELECT A , B ,

    C1 = MAX( CASE WHEN RN = 1 THEN C ELSE '0:00' END )

    ,C2 = MAX( CASE WHEN RN = 2 THEN C ELSE '0:00' END )

    ,C3 = MAX( CASE WHEN RN = 3 THEN C ELSE '0:00' END )

    ,D

    FROM CTE

    GROUP BY A , B , D

  • No, it can change.

    thanks.

  • SQL_Nw (5/23/2011)


    No, it can change.

    thanks.

    So you will need, C1, c2, c3, c4, c5.... etc etc depending on the rows, right?

  • Sorry, i was not clear, it will always be C1 c2 c3.

    Thanks

  • Thanks.

    I used your query and it did break the column into 3 columns.

    However the data is being replaced as 0:00 at most of the places.

    While it should be

    1- 61- 1:00- 2:00- 3:00 - 5/10/2011 2:00

    what am I missing.

    Thanks..

  • Change the datatype of the column C in the table variable to VARCHAR(5)...

  • My procedure worked 🙂

    I spent almost 2 days trying to figure this out. I could not have done it without your advice.

    thanks so much for your help.

  • So that someone in the future that stumbles across this thread knows, can you post your procedure here so that it can be referenced?

    Wayne
    Microsoft Certified Master: SQL Server 2008
    Author - SQL Server T-SQL Recipes


    If you can't explain to another person how the code that you're copying from the internet works, then DON'T USE IT on a production system! After all, you will be the one supporting it!
    Links:
    For better assistance in answering your questions
    Performance Problems
    Common date/time routines
    Understanding and Using APPLY Part 1 & Part 2

Viewing 10 posts - 1 through 10 (of 10 total)

You must be logged in to reply to this topic. Login to reply