------解决方案-------------------- --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
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<>'商品名'
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),