表table1
主键id  外键wid  月份    本月情况      下月计划
1         2      1       未开始        开始
2         2      2       开始          完成
3         2      3       将要完成      完成 
现在希望对表进行连接得到上月安排 
期望结果如下月份  本月情况   上月安排
1       未开始     null
2       开始       开始
3       将要完成   完成    

解决方案 »

  1.   

    select a.月份,a.本月情况,上月情况=b.本月情况
    from table1 a left join table1 b on a.月份=b.月份+1
      

  2.   

    if object_id('[TB]') is not null drop table [TB]
    go
    create table [TB] (主键id int,外键wid int,月份 int,本月情况 nvarchar(8),下月计划 nvarchar(4))
    insert into [TB]
    select 1,2,1,'未开始','开始' union all
    select 2,2,2,'开始','完成' union all
    select 3,2,3,'将要完成','完成'select * from [TB]
    SELECT A.月份,A.本月情况,B.本月情况
    FROM dbo.TB A
    LEFT JOIN TB  B ON  A.月份 - 1 = B.月份 
    /*
    月份          本月情况     本月情况
    ----------- -------- --------
    1           未开始      NULL
    2           开始       未开始
    3           将要完成     开始(3 行受影响)*/
      

  3.   

      select
       a.月份,a.本月情况,b.下月计划 as 上月安排
    from
       tb a left join tb b
    on
       a.月份-1=b.月份
      

  4.   

    ----------------------------------------------------------------
    -- Author  :fredrickhu(小F,向高手学习)
    -- Date    :2011-11-30 14:36:31
    -- Version:
    --      Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86) 
    -- Apr 22 2011 11:57:00 
    -- Copyright (c) Microsoft Corporation
    -- Enterprise Evaluation Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)
    --
    ----------------------------------------------------------------
    --> 测试数据:[tb]
    if object_id('[tb]') is not null drop table [tb]
    go 
    create table [tb]([主键id] int,[外键wid] int,[月份] int,[本月情况] varchar(8),[下月计划] varchar(4))
    insert [tb]
    select 1,2,1,'未开始','开始' union all
    select 2,2,2,'开始','完成' union all
    select 3,2,3,'将要完成','完成'
    --------------开始查询--------------------------
    select
       a.月份,a.本月情况,b.下月计划 as 上月安排
    from
       tb a left join tb b
    on
       a.月份-1=b.月份
    ----------------结果----------------------------
    /* 月份          本月情况     上月安排
    ----------- -------- ----
    1           未开始      NULL
    2           开始       开始
    3           将要完成     完成(3 行受影响)
    */
      

  5.   


    想得到的结果就是外键    月度    本月情况    上月安排
    2    1    未开始    null
    2    2    开始    开始
    2    2    开始    开始
    2    4    收尾    收尾
    2    6    完工    完工
    9    3    开始    null
      

  6.   

    create table tb(id int,wid int ,月份 int,本月情况 nvarchar(20),下月计划 nvarchar(20))
    insert into tb
    select 1, 2, 1, '未开始' ,'开始'
    union all
    select 
    2, 2, 2, '开始' ,'完成'
    union all
    select 
    3 ,2, 3, '将要完成' ,'完成'  select * from tbselect a.月份,a.本月情况,b.下月计划 as 上月安排 
    from tb as a left join tb as b on a.月份=b.月份+1