-----商品代码,进仓日期,序号
create table #temptb(spdm varchar(10),jcrq varchar(10),rn smallint)
insert into #temptb(spdm,jcrq,rn)
select 'A1A102-A','2013-09-11',1 union all
select 'A1A102-A','2013-08-05',2 union all
select 'A1A102-A','2013-08-04',3 union all
select 'A1A102-A','2013-08-04',4 union all
select 'A1A102-B','2013-08-04',1 union all
select 'A1A102-C','2013-08-04',1 union all
select 'A1A102-C','2013-03-04',2 union all
select 'A1A102-D','2013-09-04',1 union all
select 'A1A102-D','2013-03-04',2 union all
select 'A1A102-D','2013-03-04',3
/*筛选条件:
(1)如果同一个商品代码只有一条记录(rn一定是1),则为选择的数据,如:A1A102-B
(2)如果同一个商品代码有多条记录,那么取rn=1和rn=2对应的日期jcrq1和jcrq2相减
(jcrq1一定大于jcrq2),如果大于6个月,则为选择的数据,如:A1A102-C
*/
--查询结果为:
spdm
A1A102-B
A1A102-C
A1A102-D
可以用一个语句就搞定吗???????
------解决思路----------------------
--C大于6个月吗?
select a.* from
(select * from #temptb where rn=1) a left join (select * from #temptb where rn=2) b on a.spdm=b.spdm
where datediff(m,isnull(b.jcrq,''),a.jcrq)>=6
------解决思路----------------------
-- 你给的数据库,C 这个数据, 差值并不是 6 个月,而是 5 个月
select m.*
from temptb m
left join temptb n on m.spdm = n.spdm and n.rn = 2
where m.rn = 1 and (n.spdm is null or DATEDIFF(month,n.jcrq,m.jcrq)>=6 )
go
drop table temptb
go
(10 行受影响)
spdm jcrq rn
---------- ---------- ------
A1A102-B 2013-08-04 1
A1A102-D 2013-09-04 1
(2 行受影响)