Find All 'Rental' that dont have 'Bookings' within a given DateRange - sql

Proposal
What im trying to do, is allow people to input a date range, and find all 'Rentals' places that have open days between the provided date range from the user.
My Rentals have a has_many association with "bookings" which contain a start and end date.
What would be the best possible way to get every rental article that has a day that is open within that range.
Issue
I can find all the Rentals that have Bookings that dont overlap with the given time, but that doesnt account for each day. So if there was a booking from 7 Sept to 10 Sept, and the User entered the range 5 Sept to 9 Sept, that record would simply not be included, but in theory there is the 5th-7th open.
My Possible Solution
Im still thinking this problem through, so i have not started coding. But what i was going to do, is find all the Rentals that DONT have bookings that overlap with the provided Date Range, store those in a variable(because these are correct results, because it means not a single day overlaps).
Then i will find all the Rentals that have bookings that DO overlap with the provided Date Range. I will then loop through those bookings, and within that, loop through the Range of Dates provided by the user(DateRange.Each) and check if each single day is within that bookings date ranges, as soon as a single day results in a false value(meaning at least one day doesnt overlap) it will end the loop and add the associated "rental" article to the articles collected early with no overlaps at all.
Concerns
The only issue i have with this solution, is i feel it might not be very optimized or run well, im not sure. At the worst case, i would have hundreds of "rentals' and im not sure how many different "Bookings". I dont think something like this could be done in a single SQL query could it ?
Sample data
Rentals Model
name: string
has_many Bookings
Bookings Model
rental_id: integer
start_date: Date
end_date: Date
The user inputs a DateRange, i want all Rentals that have open days(none taken by a 'Booking' in the range provided.
EDIT
I have been thinking, and i think the best solution is using postgres db, which allows for arrays. Ill then store all the dates of the booking, in the array, instead of storing the range.
Postgres supports checking if all the values in an given array is present in an array in the DB. So i could check if the array of 'wanted days' is 'contained' by a DB array, if it is, it means none of the days are free.

Related

How to bypass default parameter to include a range or better SQL?

EDITED (AGAIN): added tables and two screenshots (one of Google Sheets Chart and another showing mutliple issues in DS) to help demonstrate what I am seeing.
Short Version: I have created a parameter to help me score trending topics based on the date range filter. However, I want to be able to show a range of dates' worth of data, not just a specific date's worth of data. In theory, I could make the parameter a checklist with a huge range, but that doesn't seem efficient or sustainable down the road.
Disclaimer: I am about a week into SQL and Data Studio.
Long Version: We are tracking trends over time from a specific customer data set. I'd like to make it so that when a user adjusts the time range, various topics’ " score " depends on the end date. For instance, every time the topic "Recession" is brought up, it is given a score. That score is weighted based on when it was said. I was using 365 as the highest possible score so that anything over a year is null. So if "Recession" is referenced twice, once a week ago and once today, the avg score for recession is 361.5, but if a reference is made to the topic "Talent Management" twice today, then it would have a score of 365, and so forth across a growing list of 50+ topics pertaining to 50+ specific communities we are tracking the topics across.
Here is an example:
topics
groups
entry_date
recession
A
2022-11-24
talent mgt
A
2022-11-24
recession
B
2022-11-22
economy
A
2022-11-22
recession
C
2022-11-15
talent mgt
B
2022-11-8
This score would then affect the bubble size on a chart where the Y-axis is the count of unique groups referencing the topics, and an x-axis based on the range of average scores.
The goal is to be able to see which topics are the most common across groups, which ones are emerging trends, and which ones are dated trends by having a range slider. That way users (colleagues in other departments) can play with the date range "see" the bubbles moving in location and size.
example of static chart in google sheets
I could then also use the same data and fields to measure the percentage of topics being discussed across groups based on the weighted averages against a time range.
In Goolge Sheets I can do this with an xLookUp to a tab that has a column of 0-365 and then next to it a column of 365-0 (on a tab called 'scales') and then a cell on a sheet that you can put any date as the point in time, and it affects all the scores, tables, charts, etc. (I used. =xlookup((point_in_time - entry_date), 'scales'!A:A, 'scales'!B:B, "0")
In the data studios custom SQL I used:
SELECT
*
FROM
`qRaw_data'
where
DATE(_entry_dates_) between
parse_date('%Y%m%d', #DS_START_DATE) and
parse_date('%Y%m%d', #DS_END_DATE)
AND
#pit_date_diff = date_diff(
parse_date('%Y%m%d', #ds_end_date),
_entry_dates_,
day
)
Then I created a field that is time_score of:
avg((Pit_Date_Diff-365)*(-1))
I have been googling and youtubing like crazy and think I either have to come up with a way to override the #pit_date_diff default value OR I need to use a CASE WHEN in the custom query where each time the date_diff is 1 then 365, and so on, but when I try that I get all sorts of errors.
I would like below to include all topics averaged based on all entry dates, not just those that correlate with the inputted parameter field.
currently, I can only show specific entry dates due to the parameter
I appreciate any and all help. I am a week into using data studio and am going cross-eyed Googling and YouTubing things. There is likely a better logical path to accomplish all this. Hoping for a holiday miracle.
Thanks in advance.
It turns out this was much easier than I realized... I added an AS syntax to create a column and then created a field that created the same metrics that I had in the Google Sheets:
SELECT
*,
(date_diff(parse_date('%Y%m%d', #ds_end_date), _entry_dates_,day)) AS q_time_diff
FROM
`qRaw_data`
Then the score field is: (avg(q_time_diff)-365)*(-1)
In case that helps any others in the future... ¯\(ツ)/¯
Happy Holidays!

How to Extend the End Date in a SQL Calendar Table?

I have a report that, according to users, started miscalculating dates in one field in November 2015. After some digging around, I found that one of the tables the field referenced seemed to have an end date on 2015-10-31.
The "D" field seems to represent the day of the week, with Sunday being day 1 and Saturday being 7.
Is there a way to extend the calendar so that it ends further into the future, for example 2049-12-31?
Our calendar table, for a variety of reasons, goes the the end of the current year. We have written a query that adds a new year to this table. This query takes care of most of the fields in that table. It does not touch the holiday field. That is updated manually through a web page.
We send ourselves reminders. Starting in March, we send monthly reminders that we should think about adding another year. After ensuring that the database segment has space, and that none of the definitions, such as fiscal periods, have changed, we run the query that adds a year.
Later in the year we start mailing ourselves reminders about the holidays. Then we check to see if HR has declared them, and if so, update the records accordingly.
This meets our business requirements. Yours will be different of course.

MAQL - Select all records that enclose a list of dates

I'm a bit of a noob in MAQL so I would like to know if it is possible to do the following thing :
I got a list of reservations with a Start Date and a End Date
I would like to be able to compute a metric that would give me (for reservations that match some criteria) the number of reservations that include a given night.
In the end, I want my metric to exist for each date x:
MyMetric(x) = Number of reservations with Start > x and End < x
I tried to do the following request:
SELECT COUNT(Voucher) WHERE Date(Start)<THIS AND Date(End)>THIS
but I'm having trouble setting up a report saying "Well now I want THIS to take all the values in the calendar".
(Voucher is just an attribute from my "Reservation" dimension).
Anyone knows how I can proceed ? The user manual is very difficult to read for someone who does not have an extensive experience with MAQL.
I unfortunately don't believe that what you're trying to achieve is possible with the data model you have. The reason behind this is because each date is associated with a specific action, such as the date in which a trip begins and when it ends. In order for this to work exactly how you want, it would be necessary to add a date dimension in the project that has a record for each date between the Begin and End date (e.g. Event date=generic date to capture a range of different events or snapshot date).
Hope this helps!

How would a db be designed to accept reservations everyday except holidays?

Hope the titel of my question makes sense.
We are building reservations app.
The key stumbling block right now is how to handle reservation dates.
For instance, accordding to their specs, users can make reservations everyday except during holidays.
So, if a user makes a reservation for say, 11/20/2014, if that date is available, it is presented to user for booking.
If that date is not avaialble, the next 30 available dates are presented to the user to choose from.
I have the code to do this check but my question, how do I include the date information that users can compare to the the date they selected?
Sorry guys because I am using an old browser? it won't allow me to add my comments.
So, I am adding it here.
I am just trying to clarify that what I am confused about is how to handle dates that need to be stored on the database.
For instance, whatever date a user selected as preferred event date will need to be compared to the date on our database to see if that date is available for the event.
Where and how should I store that date on the database?
One option might be a secondary table with blackout dates. Outer join to this table and then check if a date returns that is within the range of dates being requested. No joined data, then clear to book.

Core Data or NSDictionary with multiple date entries (about 800+ each year)? What would be the most easy to implement?

I'm trying to figure the best approach to solve this problem.
--
I have a "History" table that,
lists ALL years that have data.
If a user clicks a given Year, it segues to a new Table and,
lists ALL months that have data.
Clicking a given month, shows a new table that,
lists ALL days that have data.
Clicking a specific day, shows a list of one or multiple Time Stamps.
--
What is the best approach to solve this?
If user creates a Time Stamp. I need to insert it with today's date.
I also need to have the ability that if a user,
Deletes a given year. Everything in that year is deleted.
That same way,
Deleting a month, deletes everything in that month, for it's particular year.
And so on, to the point where the user should be able to delete Individual Time Stamps.
--
I thought I would Use a Dictionary with key for the "year". 2012, 2013, ...
And each retrieving another Dictionary with key for the "month", 1, 2, 3, 4, ...
And so on ... and so on ...
I also thought I could make a model using Core Data.
A Class Year representing the "Year" entity, having a relation to many possible Months, and each month, having a relation to many possible days, and days to Time *Stamps*.
And last,
I thought of creating a model with only two Entities.
Entries, with only one attribute "Date", that has a to-many relationship to "Time Stamps", receiving All the possible Time Stamps for that given day.
I am new to iOS programming. So this is all theory for me. But I did follow some Core Data tutorials and others working with NSDictionaries, protocols delegates and so on.
The "Dig In" approach as I go trough, seems more elegant. Specially because I think I could delete a particular given object in a cascade manner?
Do any of these make sense? Or is there a more obvious easy way to go about it? Also, please consider in the answer what would be easier to implement if a user chooses to delete a given entry in the "tree"
Any help is most appreciated.
Thank you advance!
Nuno
If you are going to rely on Core Data or any database engine, the best way to solve this is to use the database itself.
I see two possible solutions (there is more of course). The first, the simplest :
Entity
- timestamp
- year
- month
- day
- all_the_stuff_you_need
Make year, month and day readonly, updated along timestamp. Indexes: year, year+month, year+month+day. Easy call.
That way, you can very simple query the database, asking it to return the entities you need and only the entities you need.
A more complex setup would be:
Entity
- timestamp
- all_the_stuff_you_need
- year -> Year
- month -> Month
- day -> Day
Year
- year
- entities ->> Entity
Month
- month
- entities ->> Entity
Day
- day
- entities ->> Entity
So basically, 3 data domains for the years, months and days, months and days being immutable.
That structure is more complex, but it gives a better view of your data. You have a direct access to more information on your data as the data domains are explicit and well defined.
A third solution would be to create a date entity with year, month and day, with one entry per day. A middle ground between the two solutions above. Less interesting I think, but hey, it may suit your needs anyway.