2004.02
2004.02
2004.02
2004.02
2004.01
2004.03
2004.01
2004.01
2004.01
2004.01
2004.01
2004.03数据库中的字段如上所示,代表某年某月的信息我现在要统计,某年某月新增的企业列表新增企业列表的概念是,现有月的企业与上个月的企业进行对比,如果上个月没有,这个月有的,就叫新增
求一sql代码

解决方案 »

  1.   

    select [date],企业 from 表 a inner left join 表 b 
    on a. datediff(mm,a.[date]+'.1',b.[date]+'.1')=1
    where datediff(mm,a.[date]+'.1',getdate())=0 and b.企业 is null
      

  2.   

    改一下,不知道对否select [date],企业 from 表 a inner left join 表 b 
    on a. datediff(mm,b.[date]+'.1',a.[date]+'.1')=1
    where datediff(mm,a.[date]+'.1',getdate())=0 and b.企业 is null
      

  3.   

    支持1楼,不过写少了个条件select a.[date],a.企业 
    from 表 a inner left join 表 b 
    on datediff(mm,b.[date]+'.1',a.[date]+'.1')=1 and a.企业=b.企业
    where datediff(mm,a.[date]+'.1',getdate())=0 and b.企业 is null
      

  4.   

    create table  #T ( m varchar(7),names varchar(8))insert #T select '2004.02','01'
    insert #T select '2004.02','02'
    insert #T select '2004.02','03'
    insert #T select '2004.03','01'
    insert #T select '2004.03','02'
    insert #T select '2004.03','03'
    insert #T select '2004.03','04'select * from #T  
    where m='2004.03'
    and names not in(select names from #T where  m='2004.02')
      

  5.   

    也可以这样select * 
    from 表 a 
    where [date]=查询月份
    and not exists (
    select 1 from 表 b 
    where a.企业=b.企业 and datediff(mm,b.[date]+'.1',a.[date]+'.1')=1
    )
      

  6.   

    测试如下:
    create table c(companyname varchar(20),registerdate varchar(10))
    insert c values('a','2004.02')
    insert c values('b','2004.02')
    insert c values('c','2004.02')
    insert c values('d','2004.02')
    insert c values('a','2004.01')
    insert c values('a','2004.03')
    insert c values('b','2004.01')
    insert c values('b','2004.01')
    insert c values('b','2004.01')
    insert c values('a','2004.01')
    insert c values('a','2004.01')
    insert c values('a','2004.03')
    insert c values('e','2004.03')
    go
    --统计2月份新增
    select *
    from c d
    where registerdate='2004.02' and 
    not exists(select 1 from c where companyname=d.companyname and registerdate='2004.01')
    --统计3月份新增
    select *
    from c d
    where registerdate='2004.03' and 
    not exists(select 1 from c where companyname=d.companyname and registerdate='2004.02')
      

  7.   

    统计2月份新增,返回:
    companyname          registerdate 
    -------------------- ------------ 
    c                    2004.02
    d                    2004.02(所影响的行数为 2 行)
    统计3月份新增,返回:
    companyname          registerdate 
    -------------------- ------------ 
    e                    2004.03(所影响的行数为 1 行)