有一个表,表里包括商品id,名称,采购时间,库存量几个字段
我要按输入的时间分商品统计最近的一次库存为多少
请问各位大虾,这个sql怎么写?

解决方案 »

  1.   

    select 
        m.*
    from
        表 m
    where 
        not exists(select 1 from 表 where 商品id=m.商品id and 采购时间>m.采购时间)
      

  2.   

    select
        m.*
    from 
        表 m,
        (select 商品id,max(采购时间) as 采购时间 from 表 group by 商品id) n
    where
        m.商品id=n.商品id and m.采购时间=n.采购时间
      

  3.   

    SELECT * FROM tb a
    WHERE 1>(SELECT COUNT(1) FROM tb b WHERE b.商品ID=a.商品ID AND b.采购时间>a.采购时间 AND b.采购时间<=你输入的时间) AND 采购时间<=你输入的时间上面这条语句,假设你的库存量字段代表,每次入库后,统计出的每种商品的库存总量。如果你的库存量代表每次采购时采购的数量,那么
    SELECT a.商品id,b.采购时间,b.总库存
    FROM tb a
    LEFT JOIN 
    (SELECT 商品id,MAX(采购时间) 采购时间,SUM(库存量) 总库存 FROM tb WHERE 采购时间<=你输入的时间 GROUP BY 商品id) b
    ON b.商品id=a.商品id AND a.采购时间=b.采购时间
    WHERE a.采购时间<=你输入的时间
      

  4.   

    select 
        m.*
    from
        表 m
    where
        m.采购时间<=输入时间
        and  
        not exists(select 1 from 表 where 商品id=m.商品id and 采购时间>m.采购时间 and 采购时间<=输入时间)
      

  5.   

    把我们写的语句中的 "输入时间"改成你的时间值就可以了啊。
    比如你要查 2006-5-1 时的要求结果,那么
    m.采购时间<=输入时间
    改成
    m.采购时间<='2006-5-1'其它地方相同方法处理。这个如果我都说不清楚,那就没话说了。
      

  6.   

    declare @Date time
    set @Date='2006-07-01'select
        m.*
    from 
        表 m,
        (select 商品id,max(采购时间) as 采购时间 from 表 where 采购时间<=@Date group by 商品id) n
    where
        m.商品id=n.商品id and m.采购时间=n.采购时间
      

  7.   

    这个统计还关联了另外一个表,而这个表里的商品数据不是唯一,这样,二位统计出来的数据也就不唯一了,有什么办法呢?我把我未实现统计的sql贴出来,麻烦二位帮我改一下,谢谢!select  a.IndConMerID(商品id) as id,a.IndConMerName(商品名称) as name,a.IndConLQ(商品库存) as totalnum,a.IndConGatTim(采购时间),
    b.capability(另外一个表里要与这个表库存匹配的库存) from tbIndustryControl a,oil_firm b
    where a.IndConComID=1 and a.IndConGOID=b.OilcanId