按照名称查出同一年中其中查出连续6个月有数据的名称

数据表  
  名称         年份       月份         日期  
  a               2000         1             2000-1-10  
  a               2000         2             2000-2-10  
  a               2000         3             2000-3-10  
  a               2000         4             2000-4-10  
  a               2000         5             2000-5-10  
  a               2000         6             2000-6-10  
  b               2000         1             2000-1-10  
  b               2000         2             2000-2-10  
  b               2000         3             2000-3-10  
  b               2000         4             2000-4-10  
  c               2000         1             2000-1-10  
  c               2000         2             2000-2-10  
  c               2000         3             2000-3-10  
  c               2000         4             2000-4-10  
  c               2000         5             2000-5-10  
  c               2000         6             2000-6-10  
  c               2000         7             2000-7-10  
  c               2000         8             2000-8-10  
   
  按照名称查出同一年中其中查出连续6个月有数据的名称。  
  结果如下  
  a             2000       1-6  
  c             2000         1-8

 

declare @t table(名称 varchar(2),年份 int,月份 int,日期 datetime)
insert into @t select 'a',2000,1,'2000-1-10'
insert into @t select 'a',2000,2,'2000-2-10'
insert into @t select 'a',2000,3,'2000-3-10'
insert into @t select 'a',2000,4,'2000-4-10'
insert into @t select 'a',2000,5,'2000-5-10'
insert into @t select 'a',2000,6,'2000-6-10'
insert into @t select 'b',2000,1,'2000-1-10'
insert into @t select 'b',2000,2,'2000-2-10'
insert into @t select 'b',2000,3,'2000-3-10'
insert into @t select 'b',2000,4,'2000-4-10'
insert into @t select 'c',2000,1,'2000-1-10'
insert into @t select 'c',2000,2,'2000-2-10'
insert into @t select 'c',2000,3,'2000-3-10'
insert into @t select 'c',2000,4,'2000-4-10'
insert into @t select 'c',2000,5,'2000-5-10'
insert into @t select 'c',2000,6,'2000-6-10'
insert into @t select 'c',2000,7,'2000-7-10'
insert into @t select 'c',2000,8,'2000-8-10'

select
    a.名称,a.年份,
rtrim(a.月份)+'-'+rtrim(min(b.月份)) as 月份
from
    (
select * from @t c where not exists(select 1 from @t where 名称=c.名称 and 年份=c.年份 and 月份=c.月份-1)) a,
    (
select * from @t d where not exists(select 1 from @t where 名称=d.名称 and 年份=d.年份 and 月份=d.月份+1)) b
where
    a.名称
=b.名称 and a.年份=b.年份 and a.月份<=b.月份
group by
    a.名称,a.年份,a.月份
having
   
min(b.月份)-5>=a.月份

/*
名称   年份       月份                       
---- ----------- -------------------------
a    2000        1-6
c    2000        1-8
*/
http://topic.csdn.net/t/20061122/10/5175928.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值