日期:2014-05-18  浏览次数:20779 次

急:最后进价成本查询问题(100分)
表:
采购主表(ID,采购日期)
采购从表(存货编码,数量,进价)

采购过程中,会出现同一采购日期,可多次采购同一存货,其进价不尽相同。

现需要取“存货最后一次进价列表”,如当天有多少进价,以最大进价为准。

SQL语句该如何写,思路是什么?

------解决方案--------------------
Select 采购日期,存货编码,max(进价)
From 主表 a,从表 b Where a.ID=b.ID
Group By 采购日期,存货编码
order by 采购日期
------解决方案--------------------
create table 采购主表
( id int,
采购日期 datetime
)

create table 采购从表
(
存货编码 int,
数量 int,
进价 float
)

insert into 采购主表 values(1, '2007-01-01 ')
insert into 采购主表 values(1, '2007-01-02 ')
insert into 采购主表 values(2, '2007-01-01 ')
insert into 采购主表 values(2, '2007-01-02 ')
insert into 采购主表 values(3, '2007-01-01 ')
insert into 采购主表 values(3, '2007-01-02 ')
insert into 采购主表 values(3, '2007-01-03 ')


insert into 采购从表 values(1,10,5)
insert into 采购从表 values(1,10,6)
insert into 采购从表 values(2,10,7)
insert into 采购从表 values(2,10,8)
insert into 采购从表 values(3,10,1)
insert into 采购从表 values(3,10,2)
insert into 采购从表 values(3,10,3)

select a.id,采购日期,max(进价) as 进价 into #c from 采购主表 a,采购从表 b where a.id=b.存货编码 group by 采购日期,a.id

update b set b.进价=#c.进价 from 采购从表 b,#c where b.存货编码=#c.id

------解决方案--------------------
Select 采购日期,存货编码,max(进价)
from a inner join b on a.id=b.id
Group By 采购日期,存货编码
order by 采购日期

------解决方案--------------------
生成自增列就行了--如果表内通过单号区分不了最后一次时

select * ,id=identity(int,1,1) into #
from 进货表

select * from # a
where not exists(select 1 from # where 商品=a.商品 and id <a.id)
------解决方案--------------------
Select 采购日期,存货编码,max(进价)
From 主表 a,从表 b Where a.ID=b.存货编码
Group By 采购日期,存货编码
order by 采购日期

------解决方案--------------------
楼主问题没有说清楚啊,主表的id与从表的存货编码一样不一样.如果一样的话,那就简单了,Select 采购日期,存货编码,max(进价)
From 主表 a,从表 b Where a.ID=b.ID
where 采购日期=max(采购日期)
但是不一样的话,需要先搞明白两者之间的关系啊.
另外,如果两者的含义是相同的,两长表应该可以放在一张表中啊.