SQL - Hours of operation - datetime

I'm having a hard time wrapping my head around what seems to be a somewhat simple issue. Let's say that I have a business whose hours are 12PM - 3AM daily. Each customer gets a bonus once per day based on their initial purchase for that day. So, let's say they spend twenty bucks on their first transaction that day -- they might get a twenty percent discount on that transaction, and that's it for the day.
I'm trying to figure out the most accurate way to check the last bonus that was given and make sure that the customer is eligible for one. I can't do a simple 24-hour check, obviously, because if a customer comes in at 11 PM Monday, for instance, and again at noon Tuesday, they will not get their second bonus.
We are using a VB6 frontend for our POS, with a SQL Server 2008 R2 database. Each time a bonus is applied, it is audited on the database side, so I can easily query the last time the bonus was applied.
EDIT: I should note that, for various reasons, the solution cannot include making any changes to the structure of the database.

I'm not sure on which side (VB or SQL) you want to apply the biz logic but in either case the process should be the same: You need to persist each customer's daily hours of operation with two attributes:
Time (the time of day that they open for business)
TimeSpan (number of hours of operation)
You then check if a transaction's time is between Time and Time + TimeSpan to calculate your business logic and the customer's bonus. Both calculations are fairly trivial in VB and SQL. You just need to make sure you persist the data logically and use it consistently.

I think your answer would be cleaner if you modified it to something like:
IF #LastBonus BETWEEN #store_open AND #store_close
BEGIN
SET #BonusDue = 0
END
ELSE
BEGIN
SET #BonusDue = 1
END
where you figure the store open and close dates based on a fixed times that are added to the date part of the last bonus. Something like
Set #openTime = '12:00'
Convert(date, #LastBonus) + #openTime
And then adding the timespan (as was suggested) to get the close time. It might be a little tricky because if it's after midnight, the open time would need to be added to the previous date instead, but you could probably work this out with a CASE statement. I'd try it out myself if my baby didn't have an ear infection. Hope that is useful to you.

How about:
IF (DATEPART(dayofyear, [lastBonusTime]) <> DATEPART(dayofyear, GetDate())) ...
Where lastBonusTime is the time of the last bonus transaction ?

You can look at the problem a bit differently. If a customer is here now (GETDATE()), has it been over 24 hours since their last purchase?
So, something like
SELECT *
FROM Customers c
INNER JOIN CustomerVisits cv
ON c.CustomerId=cv.CustomerId
INNER JOIN CustomerBonus cb
ON cv.VisitId=cb.VisitId
WHERE c.CustomerId=#CustomerId
AND LastVisitDt BETWEEN
(
DATEADD(hh,12,convert(DATE, LastVisitDt))
)
AND
(
DATEADD(hh,27,convert(DATE, LastVisitDt))
)
AND DATEADD(hh,24,LastVisitDT)<=GETDATE()
I would also consider the specifics of the data--the above is NOT TUNED FOR PERFORMANCE AT ALL. I just wanted to explain my thought process.

In the interest of separating your concerns, I would add a new table, like CUSTOMER_BONUS, with these columns:
BonusStart datetime
BonusEnd datetime
CustomerID int/uniqueidentifier/whatever
TransactionID int/whatever (points to what qualified for the bonus)
When you apply a bonus for a customer for a day, write a new record into this table for the period that it applies to. Presence of a record in this table indicates that the customer is not eligible for another bonus between BonusStart and BonusEnd. When you create a new sale, look in this table. If the record exists, no bonus, but if not, apply the bonus and create a new record here.

I came up with an answer that I'm content with but it's a little kludgy and I would be more than happy to accept a more elegant answer if one is provided. Also, I haven't thoroughly tested this since it's getting late in the day, but if there are flaws in my logic, I will happily revise or accept an answer with revisions.
Basically, I'm just going to determine that the day of the week in terms of a business day is whatever day started four hours ago. This means that all the way up through 3:59 AM, "today" will be considered the day before, which is correct for these hours of operation (I'm overshooting the 3 AM closing time to account for a site deciding to stay open a little later). I then compare this span of time to the most recent time a bonus was applied to that customer's account, using the same rules. If the two match, the bonus has been applied this business day. If they are different, it has not, and the customer is eligible.
DECLARE #CustID AS int
DECLARE #LastBonus AS date
DECLARE #BonusDue AS bit
SET #LastBonus = (SELECT TOP 1 [DateTime] FROM Audit WHERE CustomerID = #CustID AND TransactionType = 'BONUS' ORDER BY [DateTime] DESC)
IF (SELECT DATEADD(hh, -4, CURRENT_TIMESTAMP)) <>
(SELECT DATEADD(hh, -4, #LastBonus))
BEGIN
SET #BonusDue = 1
END
ELSE
BEGIN
SET #BonusDue = 0
END
If I throw this in a stored procedure, I can simply throw a customer ID at it and have it spit out a bit that will show me 1 if the customer is eligible, 0 otherwise. What I don't like about it is that if a customer's hours of operation end up getting much earlier, I'll be sunk (I guess at about 7:00 AM, when simply subtracting four hours will overlap into the previous business day, but subtracting less will not be enough to reach the previous business day). So it will work for the time being, but I'd love to see a better solution.

Related

Searching between 2 different time periods

I would like to be able to have a stored procedure that will allow the user to search between 2 different time frames based off of a parameter that will say whether they are searching for results on a full 24 hour period or based off the business hours. Would a case statement in the where clause be the best choice? This will be a stored procedure that will be used in an SSRS report and the user will choose between "Calendar Day" and "Business Day" in a drop-down menu to specify the type of day defined by the parameter in the stored procedure. Thank you for any help.
I don't know if you'd need to use a CASE statement in your WHERE clause. You could probably just get away with ANDs and ORs.
WHERE
(Parameter = 'Calendar Day')
or
(Parameter = 'Business Day' and DATEPART(HOUR, DateField) between 9 and 17)
The where clause won't compare the hour when its a calendar day but when it's a business day, the time needs to be between 9 am and 5 pm.

How to put a part of a code as a string in table to use it in a procedure?

I'm trying to resolve below issue:
I need to prepare table that consists 3 columns:
user_id,
month
value.
Each from over 200 users has got different values of parameters that determine expected value which are: LOB, CHANNEL, SUBSIDIARY. So I decided to store it in table ASYSTENT_GOALS_SET. But I wanted to avoid multiplying rows and thought it would be nice to put all conditions as a part of the code that I would use in "where" clause further in procedure.
So, as an example - instead of multiple rows:
I created such entry:
So far I created testing table ASYSTENT_TEST (where I collect month and value for certain user). I wrote a piece of procedure where I used BULK COLLECT.
declare
type test_row is record
(
month NUMBER,
value NUMBER
);
type test_tab is table of test_row;
BULK_COLLECTOR test_tab;
p_lob varchar2(10) :='GOSP';
p_sub varchar2(14);
p_ch varchar2(10) :='BR';
begin
select subsidiary into p_sub from ASYSTENT_GOALS_SET where user_id='40001001';
execute immediate 'select mc, sum(ppln_wartosc) plan from prod_nonlife.mis_report_plans
where report_id = (select to_number(value) from prod_nonlife.view_parameters where view_name=''MIS'' and parameter_name=''MAX_REPORT_ID'')
and year=2017
and month between 7 and 9
and ppln_jsta_symbol in (:subsidiary)
and dcs_group in (:lob)
and kanal in (:channel)
group by month order by month' bulk collect into BULK_COLLECTOR
using p_sub,p_lob,p_ch;
forall x in BULK_COLLECTOR.first..BULK_COLLECTOR.last insert into ASYSTENT_TEST values BULK_COLLECTOR(x);
end;
So now when in table ASYSTENT_GOALS_SET column SUBSIDIARY (varchar) consists string 12_00_00 (which is code of one of subsidiary) everything works fine. But the problem is when user works in two subsidiaries, let say 12_00_00 and 13_00_00. I have no clue how to write it down. Should SUBSIDIARY column consist:
'12_00_00','13_00_00'
or
"12_00_00","13_00_00"
or maybe
12_00_00','13_00_00
I have tried a lot of options after digging on topics like "Deling with single/escaping/double qoutes".
Maybe I should change something in execute immediate as well?
Or maybe my approach to that issue is completely wrong from the very beginning (hopefully not :) ).
I would be grateful for support.
I didn't create the table function described here but that article inspired me to go back to try regexp_substr function again.
I changed: ppln_jsta_symbol in (:subsidiary) to
ppln_jsta_symbol in (select regexp_substr((select subsidiary from ASYSTENT_GOALS_SET where user_id=''fake_num''),''[^,]+'', 1, level) from dual
connect by regexp_substr((select subsidiary from ASYSTENT_GOALS_SET where user_id=''fake_num''), ''[^,]+'', 1, level) is not null) Now it works like a charm! Thank you #Dessma very much for your time and suggestion!
"I wanted to avoid multiplying rows and thought it would be nice to put all conditions as a part of the code that I would use in 'where' clause further in procedure"
This seems a misguided requirement. You shouldn't worry about number of rows: databases are optimized for storing and retrieving rows.
What they are not good at is dealing with "multi-value" columns. As your own solution proves, it is not nice, it is very far from nice, in fact it is a total pain in the neck. From now on, every time anybody needs to work with subsidiary they will have to invoke a function. Adding, changing or removing a user's subsidiary is much harder than it ought to be. Also there is no chance of enforcing data integrity i.e. validating that a subsidiary is valid against a reference table.
Maybe none of this matters to you. But there are very good reasons why Codd mandated "no repeating groups" as a criterion of First Normal Form, the foundation step of building a sound data model.
The correct solution, industry best practice for almost forty years, would be to recognise that SUBSIDIARY exists at a different granularity to CHANNEL and so should be stored in a separate table.

Updating entries in a database based on time

I have a model called "ticket" that has a start time and end time. I would like to be able to sort/divide tickets by time on the front-end. There will be 3 categories: past (now > end_time), current (start_time < now < end_time), future (now < start_time). Where now represents the real UTC time. I am thinking of having a "state" field in the ticket model which will contain the value "past", "current", or "future". I need a way to update the state of tickets based on time.
Would a cron job running every minute be an appropriate solution for this? It will iterate through all entries and do a check if the state should be updated and then perform the update if necessary. Is this solution scalable? Is there a better solution?
If it is necessary info I am thinking of using Firebase for the database and Google App Engine for the cron job.
In most cases it is the wrong approach to save data into a db which gets invalidated by time but can be calculated from the same record's data. There is also a risk of inconsistencies if the dates get updated but the cronjob didn't run yet or when dates are close to now.
I would suggest you to always calculate that info in your db queries by using the date fields. In MySQL this would work similar to this:
SELECT
(IF (end_time < NOW()) THEN 'past' ELSE IF (start_time < NOW()) THEN 'current' ELSE 'future') AS state
FROM table
Alternatively you can just fetch the start_time and end_time fields and handle the state in your application. If you want to query the entries by status, then you can also use the date columns in the filtering clauses.
This drops the need to have a cron job update the status.

Change "Expiration Date" font color if within 30 days or already expired?

Not sure the best approach to do this, the application is older which is why I'm having so much trouble generating this. I read about doing a CASE statement but I don't have much SQL experience. Any help is appreciated and answers will be respected. Thanks. Also, there's no design to this, the people who wrote the application used placeholders and all the data comes form this huge file, which is beyond me. I don't know why because I've never seen anything like this. It's a monster.
'-
Dim TemplateColumnCDLExpiration As System.Web.UI.WebControls.TemplateColumn
TemplateColumnCDLExpiration = New System.Web.UI.WebControls.TemplateColumn
If Me.AllowSorting Then
TemplateColumnCDLExpiration.SortExpression = "CDLExpiration"
End If
TemplateColumnCDLExpiration.ItemTemplate =
New JAG.WebUI.Controls.IEditGridTemplate(ListItemType.Item,
"CDLExpiration",
JAG.WebUI.Controls.tEditGridItemControlType.Label)
TemplateColumnCDLExpiration.HeaderText = "CDL Expiration"
MyBase.Columns.Add(TemplateColumnCDLExpiration)
'-
OK, I'll give you the answer to your CASE question, but you have to promise that you'll read the considerations below. :)
I'm using Oracle SQL; I don't know if the syntax is different for other SQL implementations. Here's an example of a dummy query to show the syntax:
SELECT
CASE
WHEN (sysdate - TO_DATE('04/09/2013', 'mm/dd/yyyy') > 30) THEN 'red'
ELSE 'black'
END text_color
FROM dual;
The code in the parenthesis after the WHEN is the test. It compares the current date to April 9th and asks, "Is April 9th more than 30 days ago?" If so, it returns 'red' as the value of text_color. If that condition is false, it returns 'black'. Here's a more generalized form:
SELECT
CASE
WHEN (sysdate - :date_to_check > :expiration_days) THEN 'red'
ELSE 'black'
END text_color
FROM :my_table;
Considerations
You don't need this nasty piece of logic in SQL. The check for X number of days passing since the given date is not database logic. Fetching a date is database logic, deciding how many days have elapsed from that date until today could be argued as either DB logic or business logic, but deciding the text color is definitely display logic, meaning you should be modifying your .NET code, not your SQL. What happens if you need to change the display colors? The date check remains the same, but you have to modify...your SQL? SQL modifications should only need to happen if the data that is being retrieved or stored is modified. The bottom line is that this is not a clean separation of concerns.

Time diff calculations where date and time are in seperate columns

I've got a query where I'm trying to get the hours in duration (eg 6.5 hours) between two different times.
In my database, time and date are held in different fields so I can efficiently query on just a startDate, or endDate as I never query specifically on time.
My query looks like this
SELECT COUNT(*), IFNULL(SUM(TIMEDIFF(endTime,startTime)),0) FROM events WHERE user=18
Sometimes an event will go overnight, so the difference between times needs to take into account the differences between the dates as well.
I've been trying
SELECT COUNT(*), IFNULL(SUM(TIMEDIFF(CONCAT(endDate,' ',endTime),CONCAT(startDate,' ',startTime))),0) FROM events WHERE user=18
Unfortunately I only get errors when I do this, and I can't seem to combine the two fields into a single timestamp.
Pretty sure your problem is that your concatenated values are being sent to TIMEDIFF() as strings rather than DATETIMEs. Try calling the DATETIME function on them:
SELECT COUNT(*), IFNULL(SUM(TIMEDIFF(DATETIME(CONCAT(endDate,' ',endTime)),DATETIME(CONCAT(startDate,' ',startTime)))),0) FROM events WHERE user=18
I don't have a MySQL DB in front of my to test that, but I think that or some similar form of it is what you are looking for. There's an example of it in the MySQL docs involving MICROSECOND:
http://dev.mysql.com/doc/refman/5.0/en/datetime.html
Edit: Hmm... looks like TIMEDIFF is supposed to work with strings. Worth trying anyway.
TIMEDIFF(endDate,startDate) + TIMEDIFF(endTime,startTime)

Resources