确定字段值是否满足一年范围内的最小连续年份

时间:2015-04-15 22:25:49

标签: sql sql-server sql-server-2012

鉴于下表,

 PersonID     Year
---------- ----------
1          1991
1          1992
1          1993
1          1993
2          1990
2          1991
3          1991
3          1992
3          1994

是否有一种方法可以使用SQL select查询获取PersonID,其中至少有3行,连续年份在1990到1995之间?在这种情况下,它应该只找到PersonID 1。

感谢您的帮助。

4 个答案:

答案 0 :(得分:2)

我认为以下内容应该有效:

SELECT personID
FROM
    (
        SELECT
            CASE WHEN year - min(year) OVER (PARTITION BY PersonID ORDER BY YEAR ASC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) = 2 THEN 'x' END as ConsecutiveFlag,
            PersonID
        FROM 
            (SELECT personID, year FROM table GROUP BY personID,year) subquery
        WHERE year BETWEEN 1990 and 1995   
    ) t1
WHERE ConsecutiveFlag = 'x'
GROUP BY personID

使用窗口函数按日期排序并查看两行。它将当前年份与之前两行的值进行比较,如果差异为2则我们知道我们连续几年。

外部查询过滤标记的记录并返回personid。

答案 1 :(得分:0)

尝试:

select a.PersonID from Table a
left join Table b
    on a.Personid = b.Personid and a.year = b.year + 1
left join Table c
    on a.Personid = c.Personid and b.year = c.year + 1
where b.year is not null 
    and c.year is not null
    and a.year <= 1995 and c.year >= 1990

答案 2 :(得分:0)

你可以自己加入桌子:

declare @ConsecutiveYears as integer
set @ConsecutiveYears = 3

select distinct PersonYear.PersonID
from PersonYear
join PersonYear Consecutives
on PersonYear.PersonID = Consecutives.PersonID
    and Consecutives.Year between PersonYear.Year and PersonYear.Year + @ConsecutiveYears - 1
where PersonYear.Year >= 1990 and Consecutives.Year <= 1995
Group by PersonYear.PersonID, PersonYear.Year
Having COUNT(distinct Consecutives.Year) = @ConsecutiveYears

答案 3 :(得分:0)

您可以使用2 self joins执行此操作(您将在同一personId加入表格3次,并在每个联接中将year加1,以查找每个人3年的排序时间)

架构:

create table tbl_so(PersonID int,[Year] int)
insert into tbl_so values
(1,          1991),
(1,          1992),
(1,          1993),
(1,          1993),
(2,          1990),
(2,          1991),
(3,          1991),
(3,          1992),
(3,          1994)

查询:

 select distinct t1.personId
 from tbl_so t1
 join tbl_so t2 on t1.[year]+1=t2.[year] and t1.personId=t2.personId
 join tbl_so t3 on t2.[year]+1=t3.[year] and t2.personId=t3.personId

输出:

personId
1