网 上找了很多提问的,都没有合适条件的
现把问题提出来,表如下:SQL2005
create table #tb(card char(10),datime datetime,sort int)
insert into #tb
select 'A','2014/3/10','2' union all
select 'B','2014/3/10','3' union all
select 'C','2014/3/11','1' union all
select 'C','2014/3/11','2' union all
select 'A','2014/3/11','1' union all
select 'B','2014/3/11','3' union all
select 'A','2014/3/11','2' UNION ALL
select 'A','2014/3/12','2' union all
select 'B','2014/3/12','1' union all
select 'C','2014/3/12','1' union all
select 'C','2014/3/12','2' union all
select 'A','2014/3/13','1' union all
select 'B','2014/3/13','3' union all
select 'A','2014/3/13','2' union all
select 'C','2014/3/13','2' union all
select 'C','2014/3/14','1' union all
select 'C','2014/3/14','3' union all
select 'A','2014/3/14','3' union all
select 'B','2014/3/14','3' union all
select 'A','2014/3/15','2'
以下是要求:
sort=2时 ,取days连续天数>=3
card sday eday days
A 2014/3/10 2014/3/13 4
C 2014/3/11 2014/3/13 3
sort in (2,3)时 ,取days连续天数>=2
card sday eday days
A 2014/3/10 2014/3/15 6
B 2014/3/10 2014/3/11 2
B 2014/3/13 2014/3/14 2
C 2014/3/11 2014/3/14 4
sort in (1,2,3)时 ,取days连续天数>=5
card sday eday days
A 2014/3/10 2014/3/15 6
B 2014/3/10 2014/3/14 5
------解决方案--------------------
--代码实现效率不高,但可以实现..
--DROP TABLE #tb;
create table #tb(card char(10),datime datetime,sort int)
insert into #tb
select 'A','2014/3/10','2' union all
select 'B','2014/3/10','3' union all
select 'C','2014/3/11','1' union all
select 'C','2014/3/11','2' union all
select 'A','2014/3/11','1' union all
select 'B','2014/3/11','3' union all
select 'A','2014/3/11','2' UNION ALL
select 'A','2014/3/12','2' union all
select 'B','2014/3/12','1' union all
select 'C','2014/3/12','1' union all
select 'C','2014/3/12','2' union all
select 'A','2014/3/13','1' union all
select 'B','2014/3/13','3' union all
select 'A','2014/3/13','2' union all
select 'C','2014/3/13','2' union all
select 'C','2014/3/14','1' union all
select 'C','2014/3/14','3' union all
select 'A','2014/3/14','3' union all
select 'B','2014/3/14','3' union all
select 'A','2014/3/15','2'
;WITH t AS (
SELECT *,DATEADD(DAY,-(ROW_NUMBER()
OVER ( PARTITION BY t.card ORDER BY t.datime)),t.datime) de
FROM
(
SELECT DISTINCT lt.card,lt.datime FROM #tb lt WHERE lt.sort IN(2)
)
t
)
SELECT t.card,MIN(t.datime) sday,MAX(t.datime) eday
, COUNT(1) days
FROM t GROUP BY t.card,t.de HAVING COUNT(1)>=3;
WITH t AS (
SELECT *,DATEADD(DAY,-(ROW_NUMBER()
OVER ( PARTITION BY t.card ORDER BY t.datime)),t.datime) de
FROM
(
SELECT DISTINCT lt.card,lt.datime FROM #tb lt WHERE lt.sort IN(2,3)
)
t
)
SELECT t.card,MIN(t.datime) sday,MAX(t.datime) eday
, COUNT(1) days
FROM t GROUP BY t.card,t.de HAVING COUNT(1)>=2;
WITH t AS (
SELECT *,DATEADD(DAY,-(ROW_NUMBER()
OVER ( PARTITION BY t.card ORDER BY t.datime)),t.datime) de