Skip to content
Advertisement

Transform table to smoothen records in one column

the situation (a real life situation) is:

I have a table with “log” records, for simplicity let’s assume there are only columns NAME, TIME, STATE (in reality there are few more). There are cca 1 Milion rows in which there are 100 Names (computers) and cca 10 states (productive, idle, automated, maintenance…) This can be interpreted as: *At t0 computer1 was idle, At t1 computer1 was productive… and so on.

I ask your help with replacing IDLE states with their preceding state, if there are less then 5 consecutive idles. Every other state resets the “idle counter”, if there are more then 5 idles, keep the 6th and subsequent.

This is best described on an example, so for the below gray lets assume:

  • column STATE is written inline
  • only one name
  • states described by letter ABCD..., I is the idle
  • data ordered in time, left is oldest

You can easilly see, that less then 5 Idle states were “ran” over by the previous state.

It was decided, that these short Idle periods are false positively evaluated and should be smoothened out (longer periods delayed, like in the code example). I have cca 24 1M record tables, that I need to “recalculate” to this new format. I’m not looking for a simple select, I need to perform an update, so the table stays in this new format and I can work with it in the future the same way as untill now.

I’m not a complete sql beginner, so far suspect that the way is by using OVER clause with PARTITION and PRECEDING and FOLLOWING, but this is the level I got stuck.

If needed, I may use an approach by doing *CREATE TABLE AS SELECT … * and dropping the old table. I am also pretty fluent in python, but I don’t see a way in fetching, processing and running so many updates back efectively.

Thank you very much for your advice.

Advertisement

Answer

Will this work for you (I used a counter instead of timestamps):

The output is:

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