全选,然后将值转换为Column SQL

时间:2018-08-20 06:48:53

标签: sql tsql sql-server-2014

我有下表:

------------------------
col1   col2   col3   col4
------------------------
a      asdf   1      red
b      iutt   1      red
c      jjdd   2      yellow
d      mllk   3      green
e      kkff   4      blue

我想要以下结果

-----------------------------------------------------
col1   col2   1        2        3         4
-----------------------------------------------------
a      asdf   red
b      iutt   red
c      jjdd            yellow
d      mllk                     green
e      kkff                               blue

有人知道怎么做吗?

2 个答案:

答案 0 :(得分:1)

使用枢轴

    select * from     
   (select * from table1
   ) t1        
    PIVOT (
      max(col4) for col3 in ([1],[2],[3],[4])

           )  piv

http://sqlfiddle.com/#!18/a039e/1

col1 col2    1        2       3        4
a   asdf    red     (null)  (null)  (null)
b   iutt    red     (null)  (null)  (null)
c   jjdd    (null)  yellow  (null)  (null)
e   kkff    (null)  (null)  (null)  blue
d   mllk    (null)  (null)  green   (null)

答案 1 :(得分:0)

尝试以下方法:

select col1, col2, case when col3=1 then 'red' end as 1,  case when col3=2 then 'yellow'  end as 2, case when col3=3 then 'green'  end as 3, case when col3=4 then 'blue'  end as 4
from tablename