SQL Server 2008:如何获得以前的状态

时间:2016-06-05 20:47:10

标签: sql sql-server

我需要计算当前状态为3且每个月之前状态不是2的人。 SQL如下所示:

SELECT  
    MONTH,
    COUNT(PERSON_ID) AS COUNT
FROM 
    STATUS S
WHERE 
    STATUS = 3 AND 'PREVIOUS_STATUS' <> 2
GROUP BY 
    MONTH

我的问题是:有人能告诉我如何编写SQL部分以获得当前状态= 3的人的'PREVIOUS_STATUS'吗?谢谢!

状态表的结构:

   Person_ID            Status       Month
  -------------------------------------------
    101                    1          07/15
    101                    2          09/15
    101                    3          12/15
    102                    1          02/15
    102                    3          05/15
    103                    1          03/16
    ...                   ...          ...

1 个答案:

答案 0 :(得分:2)

如果month以合理的格式存储,您可以使用outer apply

select month, count(*)
from status s outer apply
     (select top 1 s2.*
      from status s2
      where s.person_id = s2.person_id and s2.month < s.month
      order by s2.month desc
     ) as sprev
where s.status = 3 and (sprev.status is null or sprev.status = 2)
group by month;