日期:2014-05-18 浏览次数:20783 次
建议你提供详细的资料: 例如表的结构,表之间的关系,测试数据,相关算法及需要的结果。 这样有助于我们理解你的意思,更主要的是能尽快让你获得答案或解决问题的方法。
------解决方案--------------------
declare @sql varchar(8000) set @sql = 'select isnull(userid,''合计'') as 合计' select @sql = @sql + ' , sum(case convert(varchar(10),time,120) when ''' + convert(varchar(10),time,120) + ''' then price else 0 end) [' + convert(varchar(10),time,120) + ']' from (select distinct convert(varchar(10),time,120) from tb) as a set @sql = @sql + ' from tb group by userid with rollup' exec(@sql)
------解决方案--------------------
datediff(month,[date],getdate())=0筛选本月,做行转列。
------解决方案--------------------
create table pay(--支出 id int identity(1,1) primary key,--主键 pay_title varchar(100),--支出名称 pay_name varchar(100),--支出人姓名 type_id int ,--foreign key references paytype(id),--支出类型(外键) price float,--支出金额 time date,--支出时间 brief varchar(1000),--支出简介 userid int --foreign key references users(id)--支出人Id ) insert into pay(pay_title,[time],price) select 'a','2011-07-01',542.21 insert into pay(pay_title,[time],price) select 'a','2011-07-01',985.25 insert into pay(pay_title,[time],price) select 'a','2011-07-02',246.55 insert into pay(pay_title,[time],price) select 'a','2011-07-03',81849.55 insert into pay(pay_title,[time],price) select 'a','2011-07-04',57154.21 insert into pay(pay_title,[time],price) select 'a','2011-08-04',74.21 go select time,price into # from pay where CONVERT(varchar(7),[time],120)='2011-07' declare @s nvarchar(4000) select @s=isnull(@s+',','')+'['+ convert(varchar(10),time,120) +']' from (select distinct time from #)t exec('select '+@s+'from # pivot (sum([price]) for [time] in('+@s+'))b') /* 2011-07-01 2011-07-02 2011-07-03 2011-07-04 ---------------------- ---------------------- ---------------------- ---------------------- 1527.46 246.55 81849.55 57154.21 (1 行受影响) */ go drop table pay,# go