日期:2014-05-19  浏览次数:20543 次

救命啊~横向纵向问题,高手帮帮忙,完成不了就没有办法交差~
数据:
rkey       param_code     param_value
1             a                         +0.5
1             a                         -0.8
2             b                         是
2             b                         否
3             c                         1
3             c                         2

实现如下效果:
rkey       a           b           c
1           +0.5       是         1  
2           -0.5       否         2  

万分感谢~

------解决方案--------------------
使用一个临时表,可以用动态语句实现你的要求.

if object_id( 'pubs..tb ') is not null
drop table tb
go

create table tb(rkey int,param_code varchar(10),param_value varchar(10))
insert into tb(rkey,param_code,param_value) values(1, 'a ', '+0.5 ')
insert into tb(rkey,param_code,param_value) values(1, 'a ', '-0.8 ')
insert into tb(rkey,param_code,param_value) values(2, 'b ', '是 ')
insert into tb(rkey,param_code,param_value) values(2, 'b ', '否 ')
insert into tb(rkey,param_code,param_value) values(3, 'c ', '1 ')
insert into tb(rkey,param_code,param_value) values(3, 'c ', '2 ')
go

select px=(select count(1) from tb where rkey=a.rkey and param_code = a.param_code and param_value <a.param_value)+1 , * into test from tb a order by rkey , param_code , px

declare @sql varchar(8000)
set @sql = 'select px '
select @sql = @sql + ' , min(case param_code when ' ' ' + param_code + ' ' ' then param_value end) [ ' + param_code + '] '
from (select distinct param_code from test) as a
set @sql = @sql + ' from test group by px '
exec(@sql)

drop table tb,test

/*
px a b c
----------- ---------- ---------- ----------
1 +0.5 否 1
2 -0.8 是 2
*/

------解决方案--------------------
好象考慮複雜了

Create Table TEST
(rkey Int,
param_code Varchar(10),
param_value Nvarchar(10))
Insert TEST Select 1, 'a ', N '+0.5 '
Union All Select 1, 'a ', N '-0.8 '
Union All Select 1, 'a ', N '+0.6 '
Union All Select 1, 'a ', N '-0.7 '
Union All Select 2, 'b ', N '是 '
Union All Select 2, 'b ', N '否 '
Union All Select 3, 'c ', N '1 '
Union All Select 3, 'c ',