我需要计算当前状态为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
... ... ...
答案 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;