简体   繁体   中英

SQL Server 2008: HOW TO GET PREVIOUS STATUS

I need to count people whose current status is 3 and whose previous status is not 2 for each month. The SQL is like below:

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

My question is: can anyone tell me how to write the SQL part to get 'PREVIOUS_STATUS' for those people with current status =3? Thanks!

The structure for status table:

   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
    ...                   ...          ...

If month is stored in a reasonable format, you can use 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM