SQL 怎么把横向数据变成竖向数据? 150
学的不精,我只能写的比较复杂
declare @client varchar(50),@nc varchar(50)
create table #tmp1
(客户 varchar(50),昵称 varchar(50),补单日期 datetime,业务员 varchar(50),业务员序号 int)
create table #tmp2
(客户 varchar(50),昵称 varchar(50),
补单日期1 datetime,业务员1 varchar(50),
补单日期2 datetime,业务员2 varchar(50),
补单日期3 datetime,业务员3 varchar(50),
补单日期4 datetime,业务员4 varchar(50),
首选业务员 varchar(50),候选业务员 varchar(50)
)
declare @satrap1 varchar(50),@satrap2 varchar(50),@satrap3 varchar(50),@satrap4 varchar(50)
declare @date1 datetime,@date2 datetime,@date3 datetime,@date4 datetime
declare cursor_client cursor for select DISTINCT 客户,昵称 from T_CLIENT
OPEN cursor_client
fetch next from cursor_client into @client,@nc
while @@FETCH_STATUS=0
begin
insert #tmp1 select 客户,昵称,补单日期,业务员,ROW_NUMBER() over (order by 补单日期 desc) from T_CLIENT WHERE 客户=@client group by 客户,昵称,补单日期,业务员
select @satrap1=业务员,@date1=补单日期 from #tmp1 where 客户=@client and 业务员序号=1
select @satrap2=业务员,@date2=补单日期 from #tmp1 where 客户=@client and 业务员序号=2
select @satrap3=业务员,@date3=补单日期 from #tmp1 where 客户=@client and 业务员序号=3
select @satrap4=业务员,@date4=补单日期 from #tmp1 where 客户=@client and 业务员序号=4
insert #tmp2 select @client,@nc,@date1,@satrap1,@date2,@satrap2,@date3,@satrap3,@date4,@satrap4,@satrap1,@satrap2+'-'+@satrap3+'-'+@satrap4
fetch next from cursor_client into @client,@nc
end
close cursor_client
deallocate cursor_client
select * from #tmp2
drop table #tmp1
drop table #tmp2
随缘写法···可能有更精简的,我这就赶着想赶着写的 你看看能看懂不,如果觉得对不懂可以联系我
select
nn.客户 客户,
nn.昵称 昵称,
nn.补单日期1 补单日期1,
nn.业务员1 业务员1,
nn.补单日期2 补单日期2,
nn.业务员2 业务员2,
nn.补单日期3 补单日期3,
nn.业务员3 业务员3,
nn.补单日期4 补单日期4,
nn.业务员4 业务员4,
nn.业务员1 首选业务员,
nn.业务员2||'-'||nn.业务员3||'-'||nn.业务员4 候选业务员
from (
select tt.a2 客户,tt.a3 昵称,wm_concat (case when tt.top=0 then tt.a0 else '' end) 补单日期1,
wm_concat (case when tt.top=0 then tt.a4 else ''end) 业务员1,
wm_concat (case when tt.top=1 then tt.a0 else ''end) 补单日期2,
wm_concat (case when tt.top=1 then tt.a4 else ''end) 业务员2,
wm_concat (case when tt.top=2 then tt.a0 else ''end) 补单日期3,
wm_concat (case when tt.top=2 then tt.a4 else ''end) 业务员3,
wm_concat (case when tt.top=3 then tt.a0 else''end) 补单日期4,
wm_concat (case when tt.top=3 then tt.a4 else ''end) 业务员4
from
(
select zz.* from
(
select a.*,(select count(1) from a a1 where a1.a2=a.a2 and a.a0<a1.a0) top from a ORDER BY A2,A0 DESC
) zz
where
zz.top<4
) tt group by tt.a2,tt.a3
) nn