关于交叉表的问题
表A:
deptid partid dates qty remark
A001 00001 2007/08/01 500 GGGG
A001 00001 2007/08/02 1000 HHHH
.
.
.
想得到表B:
deptid partid 2007/08/01 remark 2007/08/02 remark
A001 00001 500 GGGG 1000 HHHH
需要如何解决?急!
------解决方案--------------------create table tb(deptid varchar(10),partid varchar(10) ,dates datetime,qty int,remark varchar(10))
insert into tb values( 'A001 ', '00001 ', '2007/08/01 ',500 , 'GGGG ')
insert into tb values( 'A001 ', '00001 ', '2007/08/02 ',1000, 'HHHH ')
go
declare @sql varchar(8000)
set @sql = 'select deptid,partid '
select @sql = @sql + ' , max(case dates when ' ' ' + convert(varchar(10),dates,120) + ' ' ' then qty else 0 end) [ ' + convert(varchar(10),dates,120) + '] '
+ ' , max(case dates when ' ' ' + convert(varchar(10),dates,120) + ' ' ' then remark else ' ' ' ' end) [remark] '
from (select distinct convert(varchar(10),dates,120) dates from tb) as a
set @sql = @sql + ' from tb group by deptid,partid '
exec(@sql)
drop table tb
/*
deptid partid 2007-08-01 remark 2007-08-02 remark
---------- ---------- ----------- ---------- ----------- ----------
A001 00001 500 GGGG 1000 HHHH
*/
------解决方案----------------------上为动态SQL,下为静态SQL.
create table tb(deptid varchar(10),partid varchar(10) ,dates datetime,qty int,remark varchar(10))
insert into tb values( 'A001 ', '00001 ', '2007/08/01 ',500 , 'GGGG ')
insert into tb values( 'A001 ', '00001 ', '2007/08/02 ',1000, 'HHHH ')
go
select deptid,partid,
max(case when dates = '2007-08-01 ' then qty end) '2007-08-1 ',
max(case when dates = '2007-08-01 ' then remark end) 'remark ',
max(case when dates = '2007-08-02 ' then qty end) '2007-08-2 ',
max(case when dates = '2007-08-02 ' then remark end) 'remark '
from tb
group by deptid,partid
drop table tb
/*
deptid partid 2007-08-1 remark 2007-08-2 remark
---------- ---------- ----------- ---------- ----------- ----------
A001 00001 500 GGGG 1000 HHHH
(所影响的行数为 1 行)
*/