需要SQL Server查询以获取句点

时间:2018-08-02 09:46:25

标签: sql sql-server sql-server-2008

我有下表: 每个会员每天都有一个col1值。 我需要获取每个成员col1为零的时间段。

Member_ID   | col1            | Date         
ADavis      | 0               | 11-10-2013    
ADavis      | 0               | 11-11-2013   
ADavis      | 0               | 11-12-2013    
DSmith      | 1               | 11-10-2013    
DSmith      | 0               | 11-11-2013    
FRowden     | 0               | 11-10-2013     
FRowden     | 0               | 11-11-2013    
ADavis      | 1               | 11-13-2013   
ADavis      | 0               | 11-14-2013    
DSmith      | 1               | 11-12-2013    
DSmith      | 1               | 11-13-2013    
FRowden     | 1               | 11-12-2013    
FRowden     | 0               | 11-13-2013

输出

Member_ID   | Start_date      | End_date    
ADavis      | 11-10-2013      | 11-12-2013  
ADavis      | 11-14-2013      | 11-14-2013  
DSmith      | 11-11-2013      | 11-11-2013  
FRowden     | 11-10-2013      | 11-11-2013  
FRowden     | 11-13-2013      | 11-13-2013

2 个答案:

答案 0 :(得分:2)

您可以使用row_numbers()的不同之处:

select Member_ID, min(date), max(date)
from (select *, row_number() over (partition by Member_ID order by date) seq1,
                row_number() over (partition by Member_ID, col1 order by date) seq2
      from table t
      ) t
where col1 = 0
group by Member_ID, (seq1 - seq2);

答案 1 :(得分:1)

您会发现,如果从日期中减去一个序列号,那么日期将是一个连续的值。

这提供了将连续的日期汇总在一起所需的见识:

select member_id, min(date), max(date
from (select t.*,
             row_number() over (partition by member_id order by date) as seqnum
      from t
      where col1 = 0
     ) t
group by member_id, dateadd(day, -seqnum, date);