22,209
社区成员
发帖
与我相关
我的任务
分享
AID BID Bname AKey AValue
F320 4C61 ZS 1 P1
F320 9FB1 LS 2 P2
F320 4C61 ZS 2 P2
F320 4C61 ZS 3 P3
AID BID Bname AKey1 AKey2 AKey3 AValue1 AValue2 AValue3
F320 4C61 ZS 1 2 3 P1 P2 P3
F320 9FB1 LS 0 2 0 0 P2 0
create table lee
(AID varchar(10), BID varchar(10), Bname varchar(5), AKey int, AValue varchar(5))
insert into lee
select 'F320', '4C61', 'ZS', 1, 'P1' union all
select 'F320', '9FB1', 'LS', 2, 'P2' union all
select 'F320', '4C61', 'ZS', 2, 'P2' union all
select 'F320', '4C61', 'ZS', 3, 'P3'
declare @tsql varchar(6000)
select @tsql=isnull(@tsql,'select AID,BID,Bname,')
+'max(case when AKey='+rtrim(number)+' then AKey else 0 end) ''AKey'+rtrim(number)+''','
from master.dbo.spt_values
where [type]='P'
and number between 1 and (select max(AKey) from lee)
select @tsql=@tsql
+'max(case when AKey='+rtrim(number)+' then AValue else ''0'' end) ''AValue'+rtrim(number)+''','
from master.dbo.spt_values
where [type]='P'
and number between 1 and (select max(AKey) from lee)
select @tsql=left(@tsql,len(@tsql)-1)+' from lee group by AID,BID,Bname '
exec(@tsql)
/*
AID BID Bname AKey1 AKey2 AKey3 AValue1 AValue2 AValue3
---------- ---------- ----- ----------- ----------- ----------- ------- ------- -------
F320 4C61 ZS 1 2 3 P1 P2 P3
F320 9FB1 LS 0 2 0 0 P2 0
(2 row(s) affected)
*/
select
AID
,BID
,Bname
,max(case when AKey=1 then AKey else 0 end) as AKey1
,max(case when AKey=2 then AKey else 0 end) as AKey2
,max(case when AKey=3 then AKey else 0 end) as AKey3
,max(case when AKey=1 then AValue else '0' end) as AValue1
,max(case when AKey=2 then AValue else '0' end) as AValue2
,max(case when AKey=3 then AValue else '0' end) as AValue3
from table1
group by AID,BID,Bname