I need to create a report and I am struggling with the SQL script. The table I want to query is a company_status_history table which has entries like the following (the ones that I can't figure out)
Table company_status_history
Columns:
| id | company_id | status_id | effective_date |
Data:
| 1 | 10 | 1 | 2016-12-30 00:00:00.000 |
| 2 | 10 | 5 | 2017-02-04 00:00:00.000 |
| 3 | 11 | 5 | 2017-06-05 00:00:00.000 |
| 4 | 11 | 1 | 2018-04-30 00:00:00.000 |
I want to answer to the question "Get all companies that have been at least for some point in status 1 inside the time period 01/01/2017 - 31/12/2017"
Above are the cases that I don't know how to handle since I need to add some logic of type :
- "If this row is status 1 and it's date is before the date range check the next row if it has a date inside the date range."
- "If this row is status 1 and it's date is after the date range check the row before if it has a date inside the date range."
Maybe this is what you are looking for? For these kind of questions, you need to join two instance of your table, in this case I am just joining with next record by Id, which probably is not totally correct. To do it better, you can create a new Id using a windowed function like row_number, ordering the table by your requirement criteria
Implementing second criteria:
Try with this, self-explanatory. Responds to this part of your question:
I would suggest the use of a cte and the window functions ROW_NUMBER. With this you can find the desired records. An example:
I first select all records with their leading and lagging Dates and then I perform your checks on the inclusion in the desired timespan.
I think this can be handled as a gaps and islands problem. Consider the following input data: (same as sample data of OP plus two additional rows)
You can use the following query:
to get:
Now you can identify
status = 1
islands using:Output:
Calculated field
grp
will help us identify those islands:Output:
All you want know is those records from above that overlap with the specified interval.
Demo here with somewhat more complicated use case.