有两张表aid 名称  出库时间 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
    
我每个时间段的价格不一样怎样根据出库时间段来组合其销售价格,是要用到循环吧,该怎么用

解决方案 »

  1.   

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

  2.   

    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
    */