日期:2014-05-18 浏览次数:20709 次
select 营业店,count(*) as 件数和,sum(金额) as 金额和, sum(case when datepart(mm,日期)=1 then 1 else 0 end) as [一月份件数], sum(case when datepart(mm,日期)=1 then 金额 else 0 end) as [一月金额和], sum(case when datepart(mm,日期)=2 then 1 else 0 end) as [二月份件数], sum(case when datepart(mm,日期)=2 then 金额 else 0 end) as [二月金额和] from tb group by 营业店
------解决方案--------------------
create table tb(营业店 varchar(10),金额 int,日期 varchar(10)) insert into tb select '001',10,'2011.01' insert into tb select '001',15,'2011.01' insert into tb select '001',20,'2011.02' insert into tb select '002',10,'2011.01' insert into tb select '002',30,'2011.02' insert into tb select '001',50,'2011.08' insert into tb select '002',100,'2011.08' go declare @s nvarchar(4000) select @s=isnull(@s+',','')+'['+ 日期 +']' from( select distinct 日期 from tb )t exec('select 营业店,'+@s+'from tb pivot (sum([金额]) for [日期] in('+@s+'))b') /* 营业店 2011.01 2011.02 2011.08 ---------- ----------- ----------- ----------- 001 25 20 50 002 10 30 100 (2 行受影响) */ go drop table tb
------解决方案--------------------
当然非要动态的话: declare @sql varchar(8000) set @sql = 'select 营业店 ' select @sql = @sql + ' , sum(case datepart(mm,日期) when ''' + datepart(mm,日期) + ''' then 1 else 0 end) [' + datepart(mm,日期) + '月份件数], sum(case datepart(mm,日期) when ''' + datepart(mm,日期) + ''' then 金额 else 0 end) [' + datepart(mm,日期) + '月金额和], ' from (select distinct datepart(mm,日期) from tb) as a set @sql = @sql + ' from tb group by 营业店' exec(@sql)