月份    销售量

2010-1    222
2010-2    222
2010-3    222
2010-4    222
2010-5    222
2010-6    222
2010-7   222
2010-8    222
2010-9    222
2010-10    222
2010-11    222
2010-12    222
2011-1    222
2011-2    222
2011-3    222

怎么写sql查询语句 :输入 :YYYY-MM 月份:
查询结果:
--------------------------------------------------------------------------------------------
上年同月销售量  本月销售量     上个月销售量  与上年同月比本月增减数   与本年上月比本月增减数
-------------------------------------------------------------------------------------------

解决方案 »

  1.   

    select *
    from table1 as a
    left join table1 as b on right(a.月份 ,2)=right(b.月份 ,2)
    where left(a.月份,4)='2011' AND left(b.月份,4)='2010'
      

  2.   

    改改
    select *
    from table1 as a
    left join table1 as b on right(a.月份 ,2)=right(b.月份 ,2) AND left(b.月份,4)='2010'
    where left(a.月份,4)='2011' 
      

  3.   

    use Tempdb
    go
    --> --> 
     
    if not object_id(N'Tempdb..#A') is null
    drop table #A
    Go
    Create table #A([月份] nvarchar(7),[销售量] int)
    Insert #A
    select N'2010-1',222 union all
    select N'2010-2',222 union all
    select N'2010-3',222 union all
    select N'2010-4',222 union all
    select N'2010-5',222 union all
    select N'2010-6',222 union all
    select N'2010-7',222 union all
    select N'2010-8',222 union all
    select N'2010-9',222 union all
    select N'2010-10',222 union all
    select N'2010-11',222 union all
    select N'2010-12',222 union all
    select N'2011-1',222 union all
    select N'2011-2',222 union all
    select N'2011-3',222
    Go
    --上年同月销售量 本月销售量 上个月销售量 与上年同月比本月增减数 与本年上月比本月增减数select 
    b.[销售量] AS 上年同月销售量,
    a.[销售量] as 本月销售量,
    c.[销售量] AS 上个月销售量,
    b.[销售量]-a.[销售量] as 与上年同月比本月增减数,
    c.[销售量]-a.[销售量] as 与本年上月比本月增减数
    from #A as a 
    left join #A as b on right(a.月份 ,2)=right(b.月份 ,2) AND left(b.月份,4)='2010' 
    LEFT JOIN #A AS c ON c.[月份]+'-01'=DATEADD(m,-1,a.[月份]+'-01')
    where left(a.月份,4)='2011'