I have a table that I'd like to run a SQL query on. I want to find all the customers that have a status active and have their interval_type set to interval. That part is fine, it's the next part I'm struggling with.
I want to find any orders that are to be processed between between Dec 1st 2019 and Dec 6th 2019.
The difficulty is that in my table I have the columns "interval", this can be a number between 15-75 days (and is converted to seconds) and when their order was last processed (also a unix timestamp) in the column called "last_processed".
If the "interval" (in seconds) is added to the "last_processed" (a date), does that new date fall between the 1st and 6th of Dec. How can I do that?
SELECT *
FROM subscriptions
WHERE
status = 'active' AND
interval_type = 'interval' AND
`interval` BETWEEN 1575158400 AND 1575676740;
Here's what the data looks like in my table:
You can do it this way
SELECT *,
FROM_UNIXTIME(last_processed+`interval`)
FROM subscriptions
WHERE status = 'active' AND
interval_type = 'interval'
AND (last_processed + `interval`) BETWEEN UNIX_TIMESTAMP('2019-12-01 00:00:00')
AND UNIX_TIMESTAMP('2019-12-06 23:59:59');
DBfiddle Example
Next time please use text instead or directly a dbfiddle example, than you can get an answer much earlier. That's why i posted the link for a minimal example.
Related
Found a similar question
5th BUSINESS DAY subscription SSRS
But in that case a work around -schedule for 1st of month- was suggested and accepted as the answer.
I want to know if anyone has found a clever way to make SSRS subscriptions run on a specified Business Day. I.E run on Business Day 6. This is not just to prevent the report from going out on a weekend, but also because certain Finance operations related to closing the month have an agreed upon date (EX. "Will be done by BD 3") And I need my report to run after that each month.
One comment also suggested setting up a sql agent job to calculate what BD X would be each month, and insert a SQL job for that date to kick off the Report. I can see in theory how this would work - but the subscription wouldn't be managed within SSRS then and could easily be over-looked in the future.
I have been getting by with the following imperfect code:
--: returns last day of last month (DT), but only provides a result row if we are on BusinessDay X of the month.
--No rows returned prevents the report from being processed & sent.
--SSRS Schedule must be set to run monthly in a range covering all possible Calendar Days that could be Business Day X
declare #dt datetime = Getdate(), #BDTarget int = 6
SELECT DATEADD(MONTH, DATEDIFF(MONTH, -1,#dt)-1, -1) as DT,sum(dimdate.BusinessDay) as BD
FROM DimDate
where FullDate between DATEADD(mm, DATEDIFF(mm, 0, #dt), 0) and #dt
having sum(dimdate.BusinessDay)=#BDTarget
Though recently discovered that this logic can kick off the report two days in a row, for example if we are looking for BD 6, this month July 2021 the above query returned a row on both Friday 7/9 and Sat 7/10.
You can use a data-driven subscription that runs daily.
Use a query that will only give a result on the 6th business day.
e.g.
WITH cte_6th
AS
(
SELECT *
FROM dimDate dd
WHERE dd.TheMonth = MONTH(current_timestamp)
AND dd.TheYear = YEAR(current_timestamp)
AND dd.BusinessDay = 1
ORDER BY dd.Date
OFFSET 5 ROWS
FETCH NEXT 1 ROWS ONLY
)
SELECT *
FROM cte_6th c
WHERE c.Date = CAST(current_timestamp as DATE);
How can I check if in my result set (which is formed by query shown below at the end) for every month exists every day? For example in below result set:
Date_List
08/01/2016
08/02/2016
08/03/2016
08/04/2016
08/05/2016
08/06/2016
08/07/2016
08/08/2016
08/09/2016
08/10/2016
08/11/2016
08/12/2016
08/13/2016
08/14/2016
08/15/2016
08/16/2016
08/17/2016
08/18/2016
08/19/2016
08/20/2016
08/21/2016
08/22/2016
08/23/2016
08/24/2016
08/25/2016
08/26/2016
08/27/2016
08/28/2016
08/29/2016
08/30/2016
08/31/2016
We can see that August 2016 has all days available. I want to return only such months (with all days available) with a year part of course. In this case it would be 08/16 (MM/YYYY) to return. Thus if any day for any month is missing - I do not want to return such month.
Here is the query I use to form result set:
SELECT d.`Date_List` FROM staging_area.`g360_dates_ca` d
LEFT JOIN dm_research_development.g360_pro_saas_availability a
ON d.`Date_List` = a.`DATE_OCCURRED_DATE` AND a.`IS_OUTAGE` = 'YES'
WHERE a.`DATE_OCCURRED_DATE` IS NULL AND STR_TO_DATE(d.`Date_List`,'%m/%d/%Y') <= NOW();
g360_dates_ca table contains all dates starting 01-01-2013 till 01-01-2018.
g360_pro_saas_availability - is my incidents table with details.
I have a mysql table which stores users' availability, stored in 'start' and 'end' columns as date fields.
I have a form where other users can search through the 'availabilty' with various periods like, today, tomorrow and next week . I'm trying to figure out how to construct the query to get all the rows for users who are available 'next month'.
The 'start' values maybe from today and the 'end' value might might be three months away but if next month falls between 'start' and 'end' then I would want that row returned.
The nearest I can get is with the query below but that just returns rows where 'start' falls within next month. Many thanks,
sql= "SELECT * FROM mytable WHERE start BETWEEN DATE_SUB(LAST_DAY(DATE_ADD(NOW(), INTERVAL 1 MONTH)),INTERVAL DAY(LAST_DAY(DATE_ADD(NOW(), INTERVAL 1 MONTH)))-1 DAY) AND LAST_DAY(DATE_ADD(NOW(), INTERVAL 1 MONTH))";
As you are interested in anything that happens in the full month following the current date you could try something like this:
SELECT * FROM mytable WHERE
FLOOR(start/100000000)<=FLOOR(NOW()/100000000)+1 AND
FLOOR( end/100000000)>=FLOOR(NOW()/100000000)+1
This query make use of the fact that datetime values are stored in MySql internally as a number like
SELECT now()+0
--> 20150906130640
where the digits 09 refer to the current month. FLOOR(NOW()/100000000) filters out the first digits of the number (in this case:201509). The WHERE conditions now simply test whether the start date is anywhere before the end of the next month and the end date is at least in or after the period of the next month.
(In my version I purposely left out the condition that start needs to be "after today", since a period that has started earlier seems in my eyes still applicable for your described purpose. If, however, you wanted that condition included too you could simply add an AND start > now() at the end of your WHERE clause.)
Edit
As your SQLfiddle is set-up with a date instead of a (as I was assuming) datetime column your dates will be represented differently in mumeric format like 20150907 and a simple division by 100 will now get you the desired month-number for comparison (201509):
SELECT * FROM mytable WHERE
FLOOR(start/100)<=FLOOR(NOW()/100000000)+1 AND
FLOOR( end/100)>=FLOOR(NOW()/100000000)+1
The number returned by NOW() is still a 14-digit figure and needs to be divided by 100000000. See your updated fiddle here: SQLfiddle
I also added another record ('Charlie') which does not fulfill your requirements.
Update
To better accommodate change-of-year scenarios I updated my SqlFiddle. The where clause is now based on 12*YEAR(..)+MONTH(..) type functions.
I'm reasonably new to Access and having trouble solving what should be (I hope) a simple problem - think I may be looking at it through Excel goggles.
I have a table named importedData into which I (not so surprisingly) import a log file each day. This log file is from a simple data-logging application on some mining equipment, and essentially it saves a timestamp and status for the point at which the current activity changes to a new activity.
A sample of the data looks like this:
This information is then filtered using a query to define the range I want to see information for, say from 29/11/2013 06:00:00 AM until 29/11/2013 06:00:00 PM
Now the object of this is to take a status entry's timestamp and get the time difference between it and the record on the subsequent row of the query results. As the equipment works for a 12hr shift, I should then be able to build a picture of how much time the equipment spent doing each activity during that shift.
In the above example, the equipment was in status "START_SHIFT" for 00:01:00, in status "DELAY_WAIT_PIT" for 06:08:26 and so-on. I would then build a unique list of the status entries for the period selected, and sum the total time for each status to get my shift summary.
You can use a correlated subquery to fetch the next timestamp for each row.
SELECT
i.status,
i.timestamp,
(
SELECT Min([timestamp])
FROM importedData
WHERE [timestamp] > i.timestamp
) AS next_timestamp
FROM importedData AS i
WHERE i.timestamp BETWEEN #2013-11-29 06:00:00#
AND #2013-11-29 18:00:00#;
Then you can use that query as a subquery in another query where you compute the duration between timestamp and next_timestamp. And then use that entire new query as a subquery in a third where you GROUP BY status and compute the total duration for each status.
Here's my version which I tested in Access 2007 ...
SELECT
sub2.status,
Format(Sum(Nz(sub2.duration,0)), 'hh:nn:ss') AS SumOfduration
FROM
(
SELECT
sub1.status,
(sub1.next_timestamp - sub1.timestamp) AS duration
FROM
(
SELECT
i.status,
i.timestamp,
(
SELECT Min([timestamp])
FROM importedData
WHERE [timestamp] > i.timestamp
) AS next_timestamp
FROM importedData AS i
WHERE i.timestamp BETWEEN #2013-11-29 06:00:00#
AND #2013-11-29 18:00:00#
) AS sub1
) AS sub2
GROUP BY sub2.status;
If you run into trouble or need to modify it, break out the innermost subquery, sub1, and test that by itself. Then do the same for sub2. I suspect you will want to change the WHERE clause to use parameters instead of hard-coded times.
Note the query Format expression would not be appropriate if your durations exceed 24 hours. Here is an Immediate window session which illustrates the problem ...
' duration greater than one day:
? #2013-11-30 02:00# - #2013-11-29 01:00#
1.04166666667152
' this Format() makes the 25 hr. duration appear as 1 hr.:
? Format(#2013-11-30 02:00# - #2013-11-29 01:00#, "hh:nn:ss")
01:00:00
However, if you're dealing exclusively with data from 12 hr. shifts, this should not be a problem. Keep it in mind in case you ever need to analyze data which spans more than 24 hrs.
If subqueries are unfamiliar, see Allen Browne's page: Subquery basics. He discusses correlated subqueries in the section titled Get the value in another record.
I have a Mysql Table that holds dates that are booked (for certain holiday properties).
Example...
Table "listing_availability"
Rows...
availability_date (this shows the date format 2013-04-20 etc)
availability_bookable (This can be yes/no. "Yes" = the booking changeover day and it is "available". "No" means the property is booked for those dates)
All the other dates in the year (apart from the ones with "No") are available to be booked. These dates are not in the database, only the booked dates.
My question is...
I have to make a SQL Statement that first calls the Get Date Function (not sure if this is correct terminology)
Then removes the dates from "availability_date" WHERE "availability_bookable" = "No"
This will give me the dates that are available for bookings, for the year, for a property.
Can anyone help?
Regards M
Seems like you've almost written the query.
SELECT availability_date FROM listing_availability
WHERE availability_bookable <> 'NO'
AND availability_date >= CURDATE()
AND YEAR(CURDATE()) = YEAR(availability_date)
I think I understand, and you'll obviously confirm. Your "availability_booking" has some records in it, but not every single day of the year, only those that may have had something, and not all are committed, some could have yes, some no.
So, you want to simulate All dates within a given date range... Say April 1 - July 1 as someone is looking to book a party within that time period. Instead of pre-filling your production table, you can't say that April 27th is open and available... since no such record exists.
To SIMULATE a calendar of days for a date range, you can do it using MySQL variables and join to "any" table in your database provided it has enough records to SIMULATE the date range you want...
select
#myDate := DATE_ADD( #myDate, INTERVAL 1 DAY ) as DatesForAvailabilityCheck
from
( select #myDate := '2013-03-31' ) as SQLVars,
AnyTableThatHasEnoughRows
limit
120;
This will just give you a list of dates starting with April 1, 2013 (the original #myDate is 1 day before the start date since the field selection adds 1 day to it to get to April 1, then continues... for a limit of 120 days (or whatever you are looking for range based -- 30days, 60, 90, 22, whatever). The "AnyTableThatHasEnoughRows" could actually be your "availability_booking" table, but we are just using it as a table with rows, no join or where condition, just enough to get ... 120 records.
Now, we can use this to join to whatever table you want and apply your condition. You just created a full calendar of days to compare against. Your final query may be different, but this should get it most of the way for you.
select
JustDates.DatesForAvailabilityCheck,
from
( select
#myDate := DATE_ADD( #myDate, INTERVAL 1 DAY ) as DatesForAvailabilityCheck
from
( select #myDate := '2013-03-31' ) as SQLVars,
listing_availability
limit
120 ) JustDates
LEFT JOIN availability_bookable
on JustDates.DatesForAvailabilityCheck = availability_bookable.availability_date
where
availability_bookable.availability_date IS NULL
OR availability_bookable.availability_bookable = "Yes"
So the above uses the sample calendar and looks to the availability. If no such matching date exists (via the IS NULL), then you want it meaning there is no conflict. However, if there IS a record in the table, you only want those where YES, you CAN book it, the entry on file might not be committed and CAN be in your result query of available dates.