我的一个表里面有这样两个栏位Qty 为数量 Sdate 为时间.
现在是想查某个月时分别会出现两个栏位,比如说产生Qty1为要查的某个月的数量,qty2为某个月的前一个月的数量!Qty   Sdate
100    2007-05
200    2007-06
500    2007-04
30     2007-07查2007-06时产生如下:
Qty1  Qty2 
200   100谢谢!

解决方案 »

  1.   


    select distinct (case right(Sdate,2)=month(getdate()) then Qty end ) as Qty1,
     (case right(Sdate,2)=month(getdate())-1 then Qty end ) as Qty2
    from table
      

  2.   

    declare @date varchar(20)
    set @date='2007-06'           --条件select 
       max(case when sdate=convert(varchar(7),dateadd(month,-1,@date+'-01'),120) then qty end) as qty1,
       max(case when sdate=@date then qty end) as qty2
    from tablename
      

  3.   

    create table aw(
    Qty  int , Sdate nvarchar(10))
    insert into aw
    select 100,    '2007-05'
    union select 200,    '2007-06'
    union select 500,    '2007-04'
    union select 30 ,    '2007-07'select distinct max(case when right(Sdate,2)=month('2007-06-01') then Qty end ) as Qty1,
     max(case when right(Sdate,2)=month('2007-06-01')-1 then Qty end ) as Qty2
    from aw --result
    200 100
      

  4.   

    select a.Qty Qty1,b.Qty Qty2 from 表 a left join 表 b 
    on datediff(a.Sdate+'-1',b.Sdate+'-1')=1 where a.Sdate='2007-06'
      

  5.   

    修正--借用lwl0606(寒泉) 数据
    select a.Qty Qty1,b.Qty Qty2 from aw a left join aw b 
    on datediff(mm,b.Sdate+'-1',a.Sdate+'-1')=1 where a.Sdate='2007-06'200 100
      

  6.   

    declare @t table(Qty int, Sdate char(7))
    insert @t select 100,'2007-05' union 
    select 200,'2007-06' union 
    select 500,'2007-04' union 
    select 30,'2007-07'
    declare @d char(7)
    set @d = '2007-06'
    select sum(case when sdate = @d then Qty  end)  as quy1,
    sum(case when sdate  = convert(char(7),dateadd(mm,1,@d+'-01' ),120) then qty end) as qty2
    from @t/*quy1        qty2        
    ----------- ----------- 
    200         30
    */
      

  7.   

    报错:是不是要加group by 啊? because it is not contained in an aggregate function and there is no GROUP BY clause.?????
      

  8.   

    如果还要显示其他字段的话 加 group by ,就或者两个字段 都 又 max 就不用了
      

  9.   

    --得到本月与上月的数量
    create table #t(Qty int,Sdate char(7))insert into #t values(100,'2007-05')
    insert into #t values(200,'2007-06')
    insert into #t values(500,'2007-04')
    insert into #t values(30, '2007-07')select a.Qty as Qty1,b.Qty as Qty2 from #t a,#t b
    where a.Sdate=convert(char(7),getdate(),120) 
    and b.Sdate=convert(char(7),dateadd(m,-1,getdate()),120)drop table #t