Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the unique number when it detects 'N' flag in SQL

I have a binary flag (‘Y’ or ‘N’) column, from a table, like below:

ID prev_appt_flag
1 N
2 Y
3 Y
4 N
5 N
6 Y
7 N
8 Y
9 Y
10 N
11 Y

Then, I want a row counter that will only add to its count, whenever it finds ‘N’. So for this example, the expected outcome would be:

ID prev_appt_flag final_goal
1 N 1
2 Y 1
3 Y 1
4 N 2
5 N 3
6 Y 3
7 N 4
8 Y 4
9 Y 4
10 N 5
11 Y 5

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We can use COUNT() here as an analytic function:

SELECT ID, prev_appt_flag,
       COUNT(CASE WHEN prev_appt_flag = 'N' THEN 1 END) OVER (ORDER BY ID) AS final_goal
FROM yourTable
ORDER BY ID;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading