求sql 字符类型 交叉表 向上并排
本帖最后由 jmadson 于 2013-09-06 08:20:23 编辑 求sql 字符类型 交叉表 向上并排
TEST表:
单号(sfd04) 款号(sfd05) 生产车间(sfd06)
X9372-W W11813MP 01
X9372-W W13024MF 01
X9372-W W15180BE 02
X9372-W W15431L 02
X9372-W W15431L1 02
X9372-W W52483EV 03
X9372-W W54079AC 03
X9372-W W54196K 04
通过以下语句生成交叉表
select sfd04,
case when sfd06='01' then sfd05 else '' end [01],
case when sfd06='02' then sfd05 else '' end [02],
case when sfd06='03' then sfd05 else '' end [03],
case when sfd06='04' then sfd05 else '' end [04]
from sfd_file group by sfd04,sfd05,sfd06
单号 01车间 02车间 03车间 04车间
X9372-W W11813MP
X9372-W W13024MF
X9372-W W15180BE
X9372-W W15431L
X9372-W W15431L1
X9372-W W52483EV
X9372-W W54079AC
X9372-W W54196K
但我想要以下效果,请各位帮忙解决。
单号 01车间 02车间 03车间 04车间
X9372-W W11813MP W15180BE W52483EV W54196K
X9372-W W13024MF W15431L W54079AC
X9372-W W15431L1
求sql?字符类型?交叉表?向上并排 交叉表 并排 合并 行列转换
[解决办法]
create table sfd_file
(sfd04 varchar(10), sfd05 varchar(10), sfd06 varchar(10))
insert into sfd_file
select 'X9372-W', 'W11813MP', '01' union all
select 'X9372-W', 'W13024MF', '01' union all
select 'X9372-W', 'W15180BE', '02' union all
select 'X9372-W', 'W15431L', '02' union all
select 'X9372-W', 'W15431L1', '02' union all
select 'X9372-W', 'W52483EV', '03' union all
select 'X9372-W', 'W54079AC', '03' union all
select 'X9372-W', 'W54196K', '04'
select sfd04 '单号',
isnull([01],'') '01车间',
isnull([02],'') '02车间',
isnull([03],'') '03车间',
isnull([04],'') '04车间'
from (select sfd04,sfd05,sfd06,
row_number() over(partition by sfd04,sfd06 order by getdate()) 'rn'
from sfd_file) a
pivot(max(sfd05) for sfd06 in([01],[02],[03],[04])) p
/*
单号 01车间 02车间 03车间 04车间
---------- ---------- ---------- ---------- ----------
X9372-W W11813MP W15180BE W52483EV W54196K
X9372-W W13024MF W15431L W54079AC
X9372-W W15431L1
(3 row(s) affected)
*/
create table sfd_file
(sfd04 varchar(10), sfd05 varchar(10), sfd06 varchar(10))
insert into sfd_file
select 'X9372-W', 'W11813MP', '01' union all
select 'X9372-W', 'W13024MF', '01' union all
select 'X9372-W', 'W15180BE', '02' union all
select 'X9372-W', 'W15431L', '02' union all
select 'X9372-W', 'W15431L1', '02' union all
select 'X9372-W', 'W52483EV', '03' union all
select 'X9372-W', 'W54079AC', '03' union all
select 'X9372-W', 'W54196K', '04'
select *,ID=identity(int,1,1) into #tb from sfd_file
select
px,sfd04,
max(case when sfd06='01' then sfd05 else '' end) [01],
max(case when sfd06='02' then sfd05 else '' end) [02],
max(case when sfd06='03' then sfd05 else '' end) [03],
max(case when sfd06='04' then sfd05 else '' end) [04]
from ( select *,px=(select COUNT(1)+1 from #tb where sfd06=t.sfd06 and ID<t.id) from #tb t)t
group by
px,sfd04
drop table sfd_file,#tb
/*
px sfd04 01 02 03 04
----------- ---------- ---------- ---------- ---------- ----------
1 X9372-W W11813MP W15180BE W52483EV W54196K
2 X9372-W W13024MF W15431L W54079AC
3 X9372-W W15431L1
(3 行受影响)
*/