日期:2014-05-17  浏览次数:20504 次

关于行列转换的,如图以下,如何实现


转换成



当然,数据是动态的
行列转换

------解决方案--------------------
--Create the table and insert values as portrayed in the previous example.
CREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int,
    Emp3 int, Emp4 int, Emp5 int);
GO
INSERT INTO pvt VALUES (1,4,3,5,4,4);
INSERT INTO pvt VALUES (2,4,1,5,5,5);
INSERT INTO pvt VALUES (3,4,3,5,4,4);
INSERT INTO pvt VALUES (4,4,2,5,5,4);
INSERT INTO pvt VALUES (5,5,1,5,5,5);
GO
--Unpivot the table.
SELECT VendorID, Employee, Orders
FROM 
   (SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
   FROM pvt) p
UNPIVOT
   (Orders FOR Employee IN 
      (Emp1, Emp2, Emp3, Emp4, Emp5)
)AS unpvt;
GO

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

create table 库存表(商品名 nvarchar(10),商家1 int,商家2 int,商家3 int,商家4 int)

insert 库存表 
select '商品1',25,25,25,25
union all
select '商品2',25,25,25,25
union all
select '商品3',25,25,25,25
union all
select '商品4',25,25,25,25


declare @sql nvarchar(4000)


select @sql=isnull(@sql+' union all ','')+'select [商家名]='+quotename(name,'''')+',商品名,[库存量]='+name+' from 库存表' from syscolumns where id=object_id('库存表') and name<>'商品名'


exec(@sql+' order by 商品名')

------解决方案--------------------
不会是表结构也是会变的吧,每新增加一个商家,就在表中增加一列吧??!!
如果真是这样,可以用系统表来读出此表中的全部列,筛选出商家的列,再拼SQL语句,生成所要的结果。
------解决方案--------------------
引用:
Quote: 引用:

可以使用T-SQL 中的PIVOT运算符进行透视转换  具体要转换成什么样子这样你自己写了  这个不会改变表结构  只是从表中取值的时候进行的,存到datatable以后就随便操作了

多谢啊。可以给个小例子吗

哥们  这个问题我看了下  一开始也被迷惑了   下面是我写的  实践后是可以的  
use tempdb
if OBJECT_ID('dbo.Stock','U') is not null drop table dbo.Stock;
create Table dbo.Stock
(
Goodsid int not null,
Shop1 int not null,
Shop2 int not null,
Shop3 int not null,
Shop4 int not null,
CONSTRAINT PK_Stock primary key(Goodsid)
);
Insert into dbo.Stock(Goodsid,Shop1,Shop2,Shop3,Shop4)
values
(30001,25,25,25,25),
(30002,25,25,25,25),
(30003,25,25,25,25),
(30004,25,25,25,25),