Skip to content
Advertisement

How to count SQL based on a DateTime and an other variable?

I have a SQL table with failed testresults:

Run           Test              DateTime
1             20                2020-01-01 00:01
1             20                2020-01-01 00:00
1             20                2020-01-01 00:04
2             21                2020-01-01 00:10
2             21                2020-01-01 00:03

This table is telling me that the test has failed, but I want to know if it is the first, second or third test. In the end I would like to do it with a logo where a x stands for a failed test, and a X for the concerned test, like this way:

Run           Test              StartTime              Status
1             20                2020-01-01 00:01       xXx
1             20                2020-01-01 00:00       Xxx
1             20                2020-01-01 00:04       xxX
2             21                2020-01-01 00:10       xX
2             21                2020-01-01 00:03       Xx

It has to do something with COUNT and SUM, but I couldn’t find out where to start with this case. Can you help me?

Advertisement

Answer

This seems like a weird requirement, but I think this does what you want:

select stuff(replicate('x', count(*) over (partition by run, test)),
             row_number() over (partition by run, test order by starttime), 1, 'X'
            ) as status
from t;

This uses string operations to construct the status string.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement