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

sql根据时间段查价格
有两张表

a

id 名称 出库时间

 1 电视1 2012-02-01

 2 电视1 2012-03-20

 3 电视1 2012-02-06

 4 电视2 2012-02-23
 
b

 id名称 价格 定价时间

 1 电视1 3500 2011-04-12

 2 电视1 3000 2011-12-21

 3 电视1 2800 2012-03-04

 4 电视2 4000 2012-1-16

我想得到的结果是

a.名称 b.价格 出货时间

电视1 3000 2012-02-01

电视1 3000 2012-02-06

电视1 2800 2012-03-20

电视2 4000 2012-1-16
   
我每个时间段的价格不一样

怎样根据出库时间段来组合其销售价格,是要用到循环吧,该怎么用



------解决方案--------------------
select a.名称,价格=(select top 1 from b where 出库时间>定价时间 order by 定价时间 desc),出库时间
from a

------解决方案--------------------
SQL code
create table a (id int,name nvarchar(32),out_date date)
go
insert a select 1,'电视1','2012-02-01' union all
select 2,'电视1','2012-03-20' union all
select 3,'电视1','2012-02-06' union all
select 4,'电视2','2012-02-23'
 
 create table b (id int,name nvarchar(32),price money,ord_date date)
 go
 insert b select 1,'电视1',3500,'2011-04-12' union all
select 2,'电视1',3000 ,'2011-12-21' union all
select 3,'电视1',2800 ,'2012-03-04' union all
select 4,'电视1',4000,'2012-1-16' 
 
select a.name,prices=(select top 1 price from b where out_date>ord_date order by ord_date desc),out_date
from a
 /*
 name    prices    out_date
电视1    4000.00    2012-02-01
电视1    2800.00    2012-03-20
电视1    4000.00    2012-02-06
电视2    4000.00    2012-02-23
*/