当前位置: 代码迷 >> Sql Server >> SQL动态转置,该如何解决
  详细解决方案

SQL动态转置,该如何解决

热度:8   发布时间:2016-04-24 19:58:57.0
SQL动态转置
原数据
Id V 商品名称 字段 改动前的值 改动后的值
10998 1 电脑 数量 1 2
10998 1 桌子 数量 1 2
10998 1 电脑 单价 1000 1200
10998 1 桌子 单价 200 240
10998 2 电脑 数量 2 3
10998 2 桌子 数量 2 3
10998 2 电脑 单价 1200 1100
10998 2 桌子 单价 240 220

怎么才能实现以下效果
Id V 商品名称 数量改前 数量改后 单价改前 单价改后
10998 1 电脑 1 2 1000 1200
10998 1 桌子 1 2 200 240
10998 2 电脑 2 3 1200 1100
10998 2 桌子 2 3 240 220

请大侠们帮忙。先谢了

------解决方案--------------------
实在是看不懂你的表是个怎么样子的
------解决方案--------------------

create table mh
(Id int,V int,商品名称 varchar(10),字段 varchar(10),改动前的值 int,改动后的值 int)

insert into mh
 select 10998,1,'电脑','数量',1,2 union all
 select 10998,1,'桌子','数量',1,2 union all
 select 10998,1,'电脑','单价',1000,1200 union all
 select 10998,1,'桌子','单价',200,240 union all
 select 10998,2,'电脑','数量',2,3 union all
 select 10998,2,'桌子','数量',2,3 union all
 select 10998,2,'电脑','单价',1200,1100 union all
 select 10998,2,'桌子','单价',240,220


declare @tsql varchar(6000)

select @tsql=isnull(@tsql+',','')
            +'(select top 1 b.改动前的值 from mh b 
               where b.Id=a.Id and b.V=a.V and b.商品名称=a.商品名称 and b.字段='''+字段+''') '''+字段+'改前'', '
            +'(select top 1 b.改动后的值 from mh b 
               where b.Id=a.Id and b.V=a.V and b.商品名称=a.商品名称 and b.字段='''+字段+''') '''+字段+'改后'' '
  from (select distinct 字段 from mh) t order by 字段 desc

select @tsql='select a.Id,a.V,a.商品名称,'+@tsql
            +' from mh a group by a.Id,a.V,a.商品名称 '

exec(@tsql)

/*
Id          V           商品名称       数量改前        数量改后        单价改前        单价改后
----------- ----------- ---------- ----------- ----------- ----------- -----------
10998       1           电脑         1           2           1000        1200
10998       1           桌子         1           2           200         240
10998       2           电脑         2           3           1200        1100
10998       2           桌子         2           3           240         220

(4 row(s) affected)
*/

------解决方案--------------------

use MyTest
go
if OBJECT_ID('tb') is not null
  drop table tb
create table tb(Id varchar(5),V int,[商品名称] nvarchar(10),[字段] nvarchar(10),[改动前的值] int,[改动后的值] int)
insert into tb
select '10998',1,'电脑','数量',1,2 union all
select '10998',1,'桌子','数量',1,2 union all
select '10998',1,'电脑','单价',1000,1200 union all
select '10998',1,'桌子','单价',200,240 union all
select '10998',2,'电脑','数量',2,3 union all
select '10998',2,'桌子','数量',2,3 union all
select '10998',2,'电脑','单价',1200,1100 union all
select '10998',2,'桌子','单价',240,220


select Id,V,[商品名称] 
,MAX(case [字段] when '数量' then [改动前的值] else 0 end) as '数量改前'
,MAX(case [字段] when '数量' then [改动后的值] else 0 end) as '数量改后'
  相关解决方案