关于行列转换的,如图以下,如何实现
转换成
当然,数据是动态的 行列转换
[解决办法]
--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语句,生成所要的结果。
[解决办法]
哥们 这个问题我看了下 一开始也被迷惑了 下面是我写的 实践后是可以的
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),
(30005,25,25,25,25),
(30006,25,25,25,25),
(30007,25,25,25,25),
(30008,25,25,25,25);
SELECT * from dbo.Stock;
go
declare @columns nvarchar(1000)
set @columns = ''
SELECT @columns= @columns+','+Column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (TABLE_NAME = 'Stock');
set @columns=LTRIM(STUFF(@columns,1,9,''));
declare @sql nvarchar(4000)
set @sql ='select Goodsid as Goods,shop, snum from dbo.Stock unpivot(snum for shop in('+@columns+')) as U;';
exec(@sql);
首先获取这个表的所有列,拼接字符串,传入unpivot方法,这样就可以动态获取,字符串我截的比较简单,你实际用的时候再斟酌一下吧。