zoukankan      html  css  js  c++  java
  • 复杂年月处理.sql

    --定义基本数字表
    declare @T1 table(代码 int,名称 varchar(10),参加时间 datetime,终止时间 datetime)
    insert into @T1
        select 12,'单位1','2003/04/01','2004/05/01'
        union all select 22,'单位2','2001/02/01','2003/02/01'
        union all select 42,'单位3','2000/04/01','2003/05/01'
        union all select 25,'单位5','2003/04/01','2003/05/01'

    --定义年表
    declare @NB table(代码 int,名称 varchar(10),年份 int)
    insert into @NB
        select 12,'单位1',2003
        union all select 12,'单位1',2004
        union all select 22,'单位2',2001
        union all select 22,'单位2',2002
        union all select 22,'单位2',2003

    --定义月表
    declare @YB table(代码 int,名称 varchar(10),年份 int,月份 varchar(2))
    insert into @YB
        select 12,'单位1',2003,'04'
        union all select 22,'单位2',2001,'01'
        union all select 22,'单位2',2001,'12'

    --为年表+月表数据处理准备临时表
    select top 8246 y=identity(int,1753,1)
    into #tby from
        (select id from syscolumns) a,
        (select id from syscolumns) b,
        (select id from syscolumns) c

    --为月表数据处理准备临时表
    select top 12 m=identity(int,1,1)
    into #tbm from syscolumns

    /*--数据处理--*/
    --年表数据处理
    select a.*
    from(
    select a.代码,a.名称,年份=b.y
    from @T1 a,#tby b
    where b.y between year(参加时间) and year(终止时间)
    ) a left join @NB b on a.代码=b.代码 and a.年份=b.年份
    where b.代码 is null

    --月表数据处理
    select a.*
    from(
    select a.代码,a.名称,年份=b.y,月份=right('00'+cast(c.m as varchar),2)
    from @T1 a,#tby b,#tbm c
    where b.y*100+c.m between convert(varchar(6),参加时间,112)
        and convert(varchar(6),终止时间,112)
    ) a left join @YB b on a.代码=b.代码 and a.年份=b.年份 and a.月份=b.月份
    where b.代码 is null
    order by a.代码,a.名称,a.年份,a.月份

    --删除数据处理临时表
    drop table #tby,#tbm
  • 相关阅读:
    MyEclipse使用经验总结
    CSDN-markdown编辑器使用简介
    struts2提供的校验器
    JUnit4 中@AfterClass @BeforeClass @after @before的区别对比
    JAVA中文字符编码问题详解 控制台输出
    Statement、PreparedStatement
    struts2 文件上传
    SQL RIGHT JOIN 关键字:语法及案例剖析
    SQL LEFT JOIN 关键字:语法及案例剖析
    SQL INNER JOIN 关键字:语法及案例剖析
  • 原文地址:https://www.cnblogs.com/shihao/p/2506511.html
Copyright © 2011-2022 走看看