SQL Convert column to row

后端 未结 4 640
执笔经年
执笔经年 2020-12-12 01:39

My table has the following columns:

A  |  B  |  C  |  D  |  E  |  F  

I want to displays this as follow:

MyColumn  |  MyCol         


        
相关标签:
4条回答
  • 2020-12-12 02:15
    select A as [Col 1], B as [Col 2] from table
    union all 
    select C,D from table 
    union all 
    select E,F from table
    
    0 讨论(0)
  • 2020-12-12 02:20

    This won't scale to a billion columns but...

    Select A as MyColumn, B as MyColumn2 from Table
    UNION
    Select C as MyColumn, D as MyColumn2 from Table
    UNION
    Select E as MyColumn, F as MyColumn2 from Table
    

    This query will remove the duplicates though. So say there's one record in the table

    Hello | World | Hello | World | Hello | World

    My select will only return

    Hello | World

    Sambo's will return all three...

    0 讨论(0)
  • 2020-12-12 02:29

    If I'm understanding you correctly you can do this with a union:

    SELECT A as MyColumn, B as MyColumn2
    UNION
    SELECT C as MyColumn, D as MyColumn2
    UNION
    SELECT E as MyColumn, F as MyColumn2
    

    If your datatypes aren't the same for the matching columns then you'll need to convert the datatype first, so something like:

    SELECT CONVERT(VARCHAR(10), A) as MyColumn, CONVERT(VARCHAR(10), B) as MyColumn2
    UNION
    SELECT CONVERT(VARCHAR(10), C) as MyColumn, CONVERT(VARCHAR(10), D) as MyColumn2
    UNION
    SELECT CONVERT(VARCHAR(10), E) as MyColumn, CONVERT(VARCHAR(10), F) as MyColumn2
    
    0 讨论(0)
  • 2020-12-12 02:33

    In Sql Server 2005 Unpivot operator can solve your problem. Unpivot converts columns to rows in sql server 2005.

    Hope it helps

    0 讨论(0)
提交回复
热议问题