Select 所有然后将值转换为列 SQL
Select all then convert value to Column SQL
我有以下 table:
------------------------
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
有人知道怎么做吗?
试试下面的方法:with case when
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
使用枢轴
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)
我有以下 table:
------------------------
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
有人知道怎么做吗?
试试下面的方法:with case when
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
使用枢轴
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)