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 + ,case 出货方 when +出货方+
then 数量 else 0 end) as +出货方
from (select distinct 出货方 from #lfy2) a
select @sql = @sql + from #lfy2
exec(@sql)
帮 longji(龙寂) 改一改,楼主自己测试一下吧
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 @sql = @sql + from #lfy2 group by 商品名字
exec(@sql)
--用交叉表来处理:
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.商品名字)