34,588
社区成员
发帖
与我相关
我的任务
分享
if object_id('tmpTable')is not null
drop table tmpTable
go
create table tmpTable
(supplierid varchar(2),arrivaldate varchar(8),times varchar(1),qty int)
insert tmpTable
select '01 ', '20090101 ', '1 ',10 union all
select '02 ', '20090102 ', '2 ',20 union all
select '05 ', '20090102 ', '3 ',30 union all
select '03 ', '20090101 ', '2 ',20 union all
select '04 ', '20090102 ', '2 ',20
go
select a.supplierid,a.times,a.qty,b.supplierid,b.times,b.qty from
(select ROW_NUMBER()over(order by supplierid) 序号, supplierid,times,qty from tmpTable where arrivaldate='20090101') a full join
(select ROW_NUMBER()over(order by supplierid) 序号, supplierid,times,qty from tmpTable where arrivaldate='20090102') b on a.序号=b.序号
(5 行受影响)
supplierid times qty supplierid times qty
---------- ----- ----------- ---------- ----- -----------
01 1 10 02 2 20
03 2 20 04 2 20
NULL NULL NULL 05 3 30
(3 行受影响)
create table tmpTable
(supplierid varchar(2),arrivaldate varchar(8),times varchar(1),qty int)
insert tmpTable
select '01 ', '20090101 ', '1 ',10 union all
select '02 ', '20090102 ', '2 ',20 union all
select '05 ', '20090102 ', '3 ',30 union all
select '03 ', '20090101 ', '2 ',20 union all
select '04 ', '20090102 ', '2 ',20
select *,id=identity(int,1,1) into # from tmpTable order by arrivaldate,supplierid
declare @str varchar(8000)
set @str=''
select @str=@str+',max(case when arrivaldate='''+arrivaldate+''' and seq=tb.seq then supplierid else '''' end) as supplierid,
max(case when arrivaldate='''+arrivaldate+''' and seq=tb.seq then times else '''' end) as times,
sum(case when arrivaldate='''+arrivaldate+''' then qty else 0 end) as qty'
from tmpTable
group by arrivaldate
order by arrivaldate
set @str=stuff(@str,1,1,'')
exec('select '+@str+' from (select *,seq=id-(select count(*) from # where arrivaldate<ta.arrivaldate) from # as ta) tb group by seq')
drop table tmpTable
drop table #
/*
supplierid times qty supplierid times qty
---------- ----- ----------- ---------- ----- -----------
01 1 10 02 2 20
03 2 20 04 2 20
0 05 3 30
*/