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

How to add a counter based on dates?

I have a SQL Server query that yields the following data. IdCx will always have the same FecCx.

IdCx FecCx FecTest Resultado
1234 2023-01-04 17:00:00 2023-01-02 12:00:00 0.3
1234 2023-01-04 17:00:00 2023-01-03 17:00:00 0.4
1234 2023-01-04 17:00:00 2023-01-04 19:00:00 0.4
1234 2023-01-04 17:00:00 2023-01-04 23:00:00 0.4
1234 2023-01-04 17:00:00 2023-01-05 05:00:00 0.6

For each IdCx, I require to add a chronologically ordered index based on whether FecTest occurred before of after FecCx. If it occurred before, that row number should should increase negatively. If FecTest occurred after FecCx, the row number should increase positively

IdCx FecCx FecTest Resultado Order
1234 2023-01-04 17:00:00 2023-01-02 12:00:00 0.3 -2
1234 2023-01-04 17:00:00 2023-01-03 17:00:00 0.4 -1
1234 2023-01-04 17:00:00 2023-01-04 19:00:00 0.4 1
1234 2023-01-04 17:00:00 2023-01-04 23:00:00 0.4 2
1234 2023-01-04 17:00:00 2023-01-05 05:00:00 0.6 3

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 :

Seems like you can achieve this with ROW_NUMBER and a (couple) CASE expressions:

SELECT IdCx,
       FecCx,
       FecTest,
       Resultado,
       CASE WHEN FecTest > FecCx THEN ROW_NUMBER() OVER (PARTITION BY IdCx, CASE WHEN FecTest > FecCx THEN 1 END ORDER BY FecTest)
            ELSE ROW_NUMBER() OVER (PARTITION BY IdCx, CASE WHEN FecTest > FecCx THEN 1 END ORDER BY FecTest DESC) * -1 END AS RN
FROM (VALUES(1234,CONVERT(datetime2(0),'2023-01-04 17:00:00'),CONVERT(datetime2(0),'2023-01-02 12:00:00'),0.3),
            (1234,CONVERT(datetime2(0),'2023-01-04 17:00:00'),CONVERT(datetime2(0),'2023-01-03 17:00:00'),0.4),
            (1234,CONVERT(datetime2(0),'2023-01-04 17:00:00'),CONVERT(datetime2(0),'2023-01-04 19:00:00'),0.4),
            (1234,CONVERT(datetime2(0),'2023-01-04 17:00:00'),CONVERT(datetime2(0),'2023-01-04 23:00:00'),0.4),
            (1234,CONVERT(datetime2(0),'2023-01-04 17:00:00'),CONVERT(datetime2(0),'2023-01-05 05:00:00'),0.6))V(IdCx,FecCx,FecTest,Resultado)
ORDER BY IdCx,
         FecTest;
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