item_cd   order_month   qty
A         2005/09       10
A         2005/08       5
A         2005/07       12
A         2005/06       10
B         2005/07       10
B         2005/03       12
C         2005/05       7
C         2005/03       2
C         2004/12       10
C         2004/10       15
结果如下:(最接近9月的3个月的记录)
A         2005/09       10
A         2005/08       5
A         2005/07       12
B         2005/07       10
B         2005/03       12
C         2005/05       7
C         2005/03       2
C         2004/12       10如何写这句SQL???

解决方案 »

  1.   

    select * from tb a
    where order_month in(
        select top 3 order_month from tb 
        where item_cd=a.item_cd
            and order_month<='2005/09'
        order by order_month)
      

  2.   

    select * from tb a
    where order_month in(
        select top 3 order_month from tb 
        where item_cd=a.item_cd
            and order_month<='2005/09'
        order by order_month desc)
      

  3.   

    select * from table order by item_cd,order_month
      

  4.   

    --try
    select *
    from tablename
    where datediff(month,order_month,'2005-9-30')<=3