I'm trying to find a change in Risk level for patients on a monthly basis. Using the data below. I wanted to see - How many patients had an increase in risk level in a month. Eg: In the below table John had a Risk Level as 'Low' as of 05/09/2021 and the risk increased to 'High' on 05/10/2021. So in May I'd count John if I create a bar graph for patient with increase risk
+----+------------+------------+----------------+
| ID | MemberName | Risk level | Discharge Date |
+----+------------+------------+----------------+
| 1 | John Doe | Low | 03/05/2021 |
+----+------------+------------+----------------+
| 1 | John Doe | Medium | 05/10/2021 |
+----+------------+------------+----------------+
| 1 | John Doe | High | 06/10/2021 |
+----+------------+------------+----------------+
| 2 | Sam | Medium | 05/10/2021 |
+----+------------+------------+----------------+
| 2 | Sam | Low | 05/20/2021 |
+----+------------+------------+----------------+
Query
SELECT [ID], [MemberName], [Risk level], [Discharge Date],
DATEADD(month, DATEDIFF(month, 0, [Discharge Date]), 0) as StartOfMonth,
COUNT(*) OVER (PARTITION BY ID, MONTH([Discharge Date])) as Increase_Level
--Decrease level
from Member_Risk
Expected Output
+----+------------+--------------+------------------------+------------------------+
| ID | MemberName | StartOfMonth | Increase_In_Risk_Level | Decrease_In_Risk_Level |
+----+------------+--------------+------------------------+------------------------+
| 1 | John Doe | 03/01/2021 | No | No |
+----+------------+--------------+------------------------+------------------------+
| 1 | John Doe | 05/01/2021 | Yes | No |
+----+------------+--------------+------------------------+------------------------+
| 1 | John Doe | 06/01/2021 | Yes | No |
+----+------------+--------------+------------------------+------------------------+
| 2 | Sam | 05/01/2021 | No | Yes |
+----+------------+--------------+------------------------+------------------------+
Since Sam had a change in risk level from Medium to low which is decrease the Decrease_In_Risk_Level flag is updated as 'Yes'
