行转列,这个需求有点变态
create table DispatchList
(
DLID int IDENTITY(1,1) not null,--发货主表标识
cDLCode nvarchar(30),---发货单号
dDate datetime,---发货日期
cSOCode nvarchar(30),---销售订单号
)
create table DispatchLists
(
AutoID int IDENTITY(1,1) NOT NULL,--发货单子表标识
DLID int,--发货单主表标识
Name nvarchar(50),---产品名称
iQuantity int,---数量
price int,---单价
iSum int,-- 小计=单价*数量
)
insert into DispatchList values('880922001-1','2013-9-22','880922001')
insert into DispatchList values('880922001-2','2013-9-23','880922001')
insert into DispatchList values('880922001-3','2013-9-24','880922001')
insert into DispatchList values('880922001-4','2013-9-25','880922001')
insert into DispatchList values('880922001-5','2013-9-26','880922001')
--第一次发货
insert into DispatchLists values(1,'A',10,50,500)
insert into DispatchLists values(1,'B',10,60,600)
insert into DispatchLists values(1,'C',5,70,350)
insert into DispatchLists values(1,'D',10,80,800)
--第二次发货
insert into DispatchLists values(2,'B',10,60,600)
insert into DispatchLists values(2,'C',5,70,350)
insert into DispatchLists values(2,'D',15,80,15*80)
--第三次发货
insert into DispatchLists values(3,'B',10,60,600)
insert into DispatchLists values(3,'C',5,70,350)
insert into DispatchLists values(3,'D',5,80,5*80)
--第四次发货
insert into DispatchLists values(4,'C',5,70,350)
insert into DispatchLists values(4,'E',5,80,5*80)
--第五次发货
insert into DispatchLists values(5,'C',15,70,15*70)
insert into DispatchLists values(5,'D',5,80,5*80)
SELECT a.*, b.* FROM DispatchList AS a LEFT JOIN DispatchLists AS b ON a.DLID = b.DLID
--求行转列结果:
--销售订单号 产品名称 发货日期1 发货数量1 发货金额1 发货日期2 发货数量2 发货金额2 发货日期3 发货数量3 发货金额3 累计发货数量
--880922001 A 2013-9-22 10 500 10
--880922001 B 2013-9-22 10 600 2013-9-23 10 600 2013-9-24 10 600 30
--880922001 C 2013-9-22 5 350 2013-9-23 5 350 2013-9-26 5+5+15 350+350+1050 35
--880922001 &nb