I want to write a query to display jobs that are not yet expired. I also want to show the jobs that are expiring today.
SELECT jd.`job_title`,jd.`date_expiry`,jc.`category_title`
FROM `job_details` AS jd
JOIN `job_category` AS jc
ON jc.`category_id`=jd.`category_id`
WHERE jd.`company_id`=2
AND jd.`date_expiry` >= NOW()
ORDER BY jd.`date_expiry` ASC
The query works fine for jobs that are expired yesterday or before, but it does not show jobs that are expiring today. Jobs that are expiring today are supposed to be shown to users. Please help.
I think the problem with your query is that NOW() returns a timestamp at this exact moment in time, which could be in the middle of the day, the beginning, or the end. If NOW() were in the middle of the day, then anything expiring before that point would be excluded from your query. One workaround would be to compare to the current date at midnight.
You can use TIMESTAMP(CURRENT_DATE) to achieve this, and read here for a very helpful DBA Stack Exchange question.
SELECT
jd.job_title,
jd.date_expiry,
jc.category_title
FROM job_details AS jd
INNER JOIN job_category AS jc
ON jc.category_id = jd.category_id
WHERE jd.company_id = 2 AND
jd.date_expiry >= TIMESTAMP(CURRENT_DATE) -- compare to today at midnight
ORDER BY jd.date_expiry
Related
Frontend dev here trying to get a query working.
A bit of context, we have a site where users can keep track of time and our goal is to get them to 1000 hours of time tracked.
For this we have:
a pretty default users table, with a column track_outdoors (0 or 1, since they can enable or disable it) and a meta column (json field)
A timers table, where each row has a total_time column
What I want to do is select all users who:
Have tracking enabled (track_outdoors = 1),
Do not have MORE than 1000 hours total_time tracked,
Have not received the reminder email (check if meta column has 'ac_outdoors_outdoors_reminder_sent_at')
Where the last time they tracked time was more than 2 weeks ago
I've got the basic part done, which is retrieving the users who have enabled tracking, together with their total time tracked:
SELECT
u.id,
u.firstname,
u.track_outdoors,
SUM(t.total_time) AS total
FROM
users AS u
LEFT JOIN timers AS t ON u.id = t.user_id
WHERE
u.track_outdoors = 1
AND JSON_EXTRACT(u.meta, '$.ac_outdoors_outdoors_reminder_sent_at') IS NULL
GROUP BY
u.id
Now the two parts I'm having trouble with is using the sum to check if the total_time is smaller than 1000 and checking if the last time tracking was more than two weeks ago.
Apparently I cant use the SUM inside of the WHERE statement.
I tried searching on how to do a where last relationship is x time ago, but all I find is how to query records x days ago. (It needs to be the latest record x days ago, if that makes sense).
I think for the SUM in the WHERE statement I might need to use a subquery, but I'm not sure if that's true or how I'm supposed to do that. For the 2 weeks ago check, I understand how to check where the date is two weeks ago but not how to check that for the latest record for the user.
Any help would be much appreciated!
Thanks to the comment/answer provided by #Akina I was able to finish my query.
The result is:
SELECT
u.id,
u.firstname,
u.track_outdoors,
SUM(t.total_time) AS total
FROM
users AS u
LEFT JOIN timers AS t ON u.id = t.user_id
WHERE
u.track_outdoors = 1
AND JSON_EXTRACT(u.meta, '$.ac_outdoors_outdoors_reminder_sent_at') IS NULL
GROUP BY
u.id
HAVING total < 1000 AND MAX( t.created_at ) < CURRENT_DATE - INTERVAL 2 WEEK
So I needed to use HAVING for checking the total and MAX to check for the date of the tracker to be more than two weeks ago.
I have a query that brings back dates of inbound and outbound payments, and for each outbound payment i want to calculate the number of days since the previous inbound payment.
E.g.
SELECT
ps.clientid AS 'clientid',
psi.id AS 'scheduleid',
case when psi.status IN (4,5,6) then 'IB' when psi.status = 9 then 'OB' END AS 'type',
case when psi.status IN (4,5,6) then FROM_UNIXTIME(psit.date_cleared_on) when psi.status = 9 then FROM_UNIXTIME(psi.due_date) END AS 'date'
FROM payment_schedule_inbound psi
LEFT JOIN payment_schedule_inbound_transaction psit ON psit.payment_schedule_inbound_id = psi.id
INNER JOIN payment_schedule ps ON ps.id = psi.payment_schedule_id
WHERE psi.`status` IN (4,5,6,9)
AND ps.clientid IN (913244,913174) /*example id's, will usually run on multiple at same time or likely the full book*/
ORDER BY ps.clientid,(case when psi.status = 9 then psi.due_date else psit.date_cleared_on END)
(my CRM system stores dates as unixtime for some reason - not my fault, i didn't build the thing!)
What i want to do is, for each 'OB' event, display the datediff between that date and the previous 'IB' event for that clientid. In an ideal world i'd then like to have it only show the number of working days (excluding weekends), but that's whole other can of worms i can get to later!
I know the theory behind it would be to join the query back in on itself and get the max(date) of an IB event where the date is less than the date of the 'OB' event, but i'm just a layman and it's all got a bit much for me!
Any advice would be appreciated.
Thanks,
Ben.
In short: MySQL - I need to bring company that have been inactive for a while (or 365 days for the fiddle example).
How I check this? each company have at least a contact, who is related to an event, and each event have (many) subevents, in this last table I have the last date of activity, the days that considers that one company is on inactivity is decided for the user, I don't have problem to do this calculation
sql.Append("where DATEDIFF(CURDATE(),DATE(lastdate)) > " +days.ToString()+ "
The problem is, that this check ALL the subevents, so this not only check the last date, but every date... and this means, bad output.
I was thinking on subqueries to get or the max date on the subevent of a contact, or the max date of the subevent of a event.
Then with a friend we get close with sort of this, but the query is infinite.
select * from subevent se
where DATEDIFF(CURDATE(),DATE(
(select se2.dates from subevent se2
where se2.dates in
(select max(se3.dates)
from subevent se3
where se.idev = se3.idev)
group by se2.dates)));
I'm stuck and I would appreciate the help...
Tried group by, subquery and MAX (obviously max is necessary, but don't how where to apply...)
https://www.db-fiddle.com/f/wgSQGn7Z26tHnwm6nAaNSA/8
(On the Fiddle link, should only bring the companyname2 and companyname4)
You can use aggregation to get the last subevent date for each company. Then filter using a having clause:
select c.idcomp
from contact c join
events e
on e.idcont = c.idcont join
subevent se
on se.idev = e.idev
group by c.idcomp
having max(se.date) < current_date - interval 365 day;
Here is a db-fiddle.
I am creating a pipeline report so we can count opportunities that have been added each week.
My query is:
SELECT
sum(IF(o.date_entered > date_sub(now(), INTERVAL 1 WEEK), 1,0))
Pretty simple and works. The problem is, sales now also wants to count any opportunity as new that has been moved out of a loss status. So, I left-joined to an audit table to include this use case. But now, it counts every instance of the audit table for a given account where the field = sales_stage and the before_value is a loss status. So, and not that this would happen that often if ever, but if an opportunity moves from loss to lead, back to loss, and back to lead, it will count it as 2 new opportunities. I just want to get the latest instance of field=sales_stage and before_value is a loss status, and count that one time.
I want something like a sub-query in the left join, and I keep trying to use MAX, but nothing's working. Here's part of my join:
INNER JOIN opportunities o ON ao.opportunity_id=o.id
LEFT JOIN opportunities_audit oa ON o.id=oa.parent_id
AND after_value_string = 'Loss'
AND date_created > date_sub(now(), INTERVAL 1 WEEK)
Does anybody know the solution to this type of problem? Thank you in advance for any advice!
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.