2个表,
一个是商品表 包括: 商品代号 商品名字
一个是出货纪录 : 商品代号 出货方 数量 时间
如何才能生成如下这样一个表呢?
出货方1 出货方2 出货方3 出货方4 ....
商品名字 x x x x
商品名字 x x x x
其中x是最后一次出货数量,没有记录则空白。
想了一天了 ~```头大ing,求教各位高人,select语句也行,存储过程也行。
...全文
237打赏收藏
求教查询,或者存储过程。
2个表, 一个是商品表 包括: 商品代号 商品名字 一个是出货纪录 : 商品代号 出货方 数量 时间 如何才能生成如下这样一个表呢? 出货方1 出货方2 出货方3 出货方4 .... 商品名字 x x x x 商品名字 x x x x 其中x是最后一次出货数量,没有记录则空白。 想了一天了 ~```头大ing,求教各位高人,select语句也行,存储过程也行。
select 商品代号,出货方,数量 into #lfy1 from table2 as a where 时间=(select max(时间) from table2 as b where b.出货方=a.出货方)
select a.商品名字,b.出货方,b.数量 into #lfy2 from table1 as a inner join table2 as b on a.商品代号=b.商品代号
declare @sql varchar(8000)
set @sql = 'select 商品名字,'
select @sql = @sql + ', sum(case 出货方 when '''+出货方+'''
then 数量 else 0 end) as '+出货方
from (select distinct 出货方 from #lfy2) a
select 商品代号,出货方,数量 into #lfy1 from table2 as a where 时间=(select max(时间) from table2 as b where b.出货方=a.出货方)
select a.商品名字,b.出货方,b.数量 into #lfy2 from table1 as a inner join table2 as b on a.商品代号=b.商品代号
declare @sql varchar(8000)
set @sql = 'select 商品名字,'
select @sql = @sql + ',case 出货方 when '''+出货方+'''
then 数量 else 0 end) as '+出货方
from (select distinct 出货方 from #lfy2) a
create table 商品表(商品代号 varchar(10),商品名字 varchar(50))
insert into 商品表
select '001','A产品'
union all select '002','B产品'
create table 出货记录(商品代号 varchar(10),出货方 varchar(50),数量 int,时间 datetime)
insert into 出货记录
select '001','A单位',100,'2002-02-02'
union all select '001','B单位',10,'2003-02-02'
union all select '002','A单位',800,'2002-03-02'
union all select '002','C单位',1000,'2002-12-02'
union all select '002','D单位',1080,'2002-02-22'
union all select '001','A单位',1060,'2003-12-02'
--用交叉表来处理:
declare @sql varchar(8000),@imax int,@cmax varchar(20)
set @sql='select a.商品名字'
select @sql=@sql+',['+出货方+']=max(case 出货方 when '''+出货方+''' then 数量 end)'
from (select distinct 出货方 from 出货记录) a
exec(@sql+' from 商品表 a inner join 出货记录 b on a.商品代号=b.商品代号
where b.时间 in (select 时间 from(select 出货方,时间=max(时间) from 出货记录 where 商品代号=a.商品代号 group by 出货方) aa)
group by a.商品名字')
--用交叉表来处理:
declare @sql varchar(8000),@imax int,@cmax varchar(20)
set @sql='select a.商品名字'
select @sql=@sql+',['+出货方+']=max(case 出货方 when '''+出货方+''' then 数量 end)'
from (select distinct 出货方 from 出货记录) a
exec(@sql+' from 商品表 a inner join 出货记录 b on a.商品代号=b.商品代号
where b.时间 in (select 时间 from(select 出货方,时间=max(时间) from 出货记录 where 商品代号=a.商品代号 group by 出货方) aa)
group by a.商品名字')
--用交叉表来处理:
declare @sql varchar(8000),@imax int,@cmax varchar(20)
set @sql='select a.商品名字'
select @sql=@sql+',['+出货方+']=max(case 出货方 when '''+出货方+''' then 数量 end)'
from (select distinct 出货方 from 出货记录) a
exec(@sql+' from 商品表 a inner join 出货记录 b on a.商品代号=b.商品代号
where b.时间 in (select 时间 from(select 出货方,时间=max(时间) from 出货记录 where 商品代号=a.商品代号 group by 出货方) aa)
group by a.商品名字')