日期:2014-05-18 浏览次数:20555 次
--> 测试数据:[test]
if object_id('[test]') is not null
drop table [test]
create table [test](
[Fbillno] varchar(10),
[Finterid] int,
[Fstatus] int,
[Fitemid] int,
[Fauxqty] numeric(13,10),
[Fdate] varchar(7),
[Fqty] numeric(5,2)
)
go
insert [test]
select 'WORK005525',6595,3,28086,100.0000000000,'2012-05',100.00 union all
select 'WORK005526',6602,3,28090,300.0000000000,'2012-05',174.00 union all
select 'WORK005526',6602,3,28090,300.0000000000,'2012-06',126.00
declare @str varchar(2000)
set @str=''
select
@str=@str+',['+[Fdate]
+']=max(case when [Fdate]='
+quotename([Fdate],'''')+' then [Fqty] else 0 end)'
from
test
group by
[Fdate]
print @str
set @str='select Fbillno,Finterid,Fstatus,Fitemid,Fauxqty'
+@str+',sum(Fqty) as Fqty from test
group by Fbillno,Finterid,Fstatus,Fitemid,Fauxqty'
exec(@str)
/*
Fbillno Finterid Fstatus Fitemid Fauxqty 2012-05 2012-06 Fqty
------------------------------------------
WORK005525 6595 3 28086 100.0000000000 100.00 0.00 100.00
WORK005526 6602 3 28090 300.0000000000 174.00 126.00 300.00
*/
------解决方案--------------------
select fbillno,finterid,fstatus,fitemid,fauxqty,
max(case when fdate='2012-05'then fqty else 0 end)[2012-05],
max(case when fdate='2012-06'then fqty else 0 end)[2012-06],
sum(fqty)[fqty]
from test group by fbillno,finterid,fstatus,fitemid,fauxqty