1、创建测试表,
create table test_fee(userid number, feeid number, fee number);
2、插入测试数据
insert into test_fee values(1,1001,80);
insert into test_fee values(1,1002,70);
insert into test_fee values(1,1003,90);
insert into test_fee values(1,1004,60);
insert into test_fee values(2,1001,99);
insert into test_fee values(2,1002,66);
insert into test_fee values(2,1001,55);
3、查询表中所有记录,select t.*, rowid from test_fee t,
4、编写sql,按userid汇总,根据不同的feeid,进行行转列汇总,
select userid,
sum(case when feeid = 1001 then fee else 0 end) as fee_1001,
sum(case when feeid = 1002 then fee else 0 end) as fee_1002,
sum(case when feeid = 1003 then fee else 0 end) as fee_1003,
sum(case when feeid = 1004 then fee else 0 end) as fee_1004
from test_fee t
group by userid
--用动态sql实现行转列。因用到了row_number,只适用于sql server 2005及以上版本
--测试数据
with
[user](ID,name,roleid)
as(
select 1,'bobo','r1' union all
select 2,'coco','r1' union all
select 3,'dodo','r1' union all
select 4,'eoeo','r2' union all
select 5,'fofo','r2'),
[role](ID,name)
as(
select 'r1','admin' union all
select 'r2','user')
--两表联合查询后暂存入临时表
select b.ID roleid,b.name rolename,a.name username,row_number() over (partition by b.ID order by a.ID) seq
into #t
from [user] a
inner join [role] b on a.roleid=b.ID;
--拼接动态sql
declare @sql varchar(max);
set @sql='';
select @sql=@sql+
',max(case seq when '+cast(tt.seq as varchar)+' then username else '''' end) user'+cast(tt.seq as varchar)
from (select distinct seq from #t) tt
order by seq;
set @sql='select rolename'+@sql+' from #t group by roleid,rolename';
--打印动态sql
select @sql;
--执行动态sql
exec(@sql);
--删除临时表
drop table #t;
生成的动态sql为:
select rolename,
max(case seq when 1 then username else '' end) user1,
max(case seq when 2 then username else '' end) user2,
max(case seq when 3 then username else '' end) user3
from #t group by roleid,rolename
最终查询结果为:
left join user b on a.id = b.roleid
-------------------
如果有sql能写出来你需要的那样查询结果, 那不是在向r1添加一条记录就有1列了呀.这样查出来怎么在程序层面取值啊.
-----------------
我感觉 应该是你吧需求理解错了吧
广告 您可能关注的内容 |