如何转置此显示。
SeqNo Step Date By
1 Quoted 2018-03-01 Person1
2 Checked 2018-03-02 Person2
3 Authorized 2018-03-02 Person3
4 Approved 2018-03-03 Person4
进入此显示。
1 2 3 4
Quoted Checked Authorized Approved
2018-03-01 2018-03-02 2018-03-02 2018-03-03
Person1 Person2 Person3 Person4
答案 0 :(得分:4)
您必须使用 unpivot and pivot 语法的组合来实现您的结果,并最终将所有内容转换为与varchar(max)相同的兼容数据类型
的 live demo here 强>
请参阅下面的查询
create table srcTable (SeqNo int, Step varchar(10), [Date] date, [By] varchar(10));
insert into srcTable values
(1,'Quoted','2018-03-01','Person1')
,(2,'Checked','2018-03-02','Person2')
,(3,'Authorized','2018-03-02','Person3')
,(4,'Approved','2018-03-03','Person4')
select [1],[2],[3],[4] from
(
select
SeqNo,
[c2]=cast(Step as varchar(max)) ,
[c3]=cast([Date] as varchar(max)),
[c4]=cast([By] as varchar(max))
from
srcTable
)s
unpivot
(
value for data in ([c2],[c3],[c4])
)up
pivot
(
max(value) for SeqNo in ([1],[2],[3],[4])
)p