How to compare two dates MySQL - mysql

I'm trying to create a report function, I store in my database some data with a specific value (closeDate), this value can be only 7th or 21nd, here is an example of my table:
What I want to do is every 22nd execute a query to select all the register which have Status = "Active" or "On approve" and CloseDate < to 22nd (Curdate). I have this query, but this query show me all exactly like in the image and what I expect is that the query show me only the data from Id = 00001 and 00003 because Id 00002 CloseDate(2016-10-21) it's not < to 2016-09-22 (curdate).
SELECT tbl_usuarios.Correo, tbl_alertas.Id, tbl_alertas.Purpose, tbl_alertas.Status, tbl_alertas.OpenDate, tbl_alertas.CloseDate, tbl_alertas.Owner, tbl_alertas.ValueStream, tbl_alertas.Family
FROM tbl_usuarios
INNER JOIN tbl_alertas ON tbl_usuarios.Nombre = tbl_alertas.Owner
WHERE STATUS = 'On approve' OR STATUS = 'Active' AND CloseDate < CURDATE()
What I'm doing wrong?

You may need to rearrange your clauses in your WHERE condition. It has both OR and AND so it may not be interpreted as you expect.
I would try something like this:
WHERE (STATUS = 'On approve' OR STATUS = 'Active') AND CloseDate < CURDATE()
Or you can simplify this using IN:
WHERE STATUS IN ('On approve', 'Active') AND CloseDate < CURDATE()

SELECT tbl_usuarios.Correo, tbl_alertas.Id, tbl_alertas.Purpose, tbl_alertas.Status, tbl_alertas.OpenDate, tbl_alertas.CloseDate, tbl_alertas.Owner, tbl_alertas.ValueStream, tbl_alertas.Family
FROM tbl_usuarios
INNER JOIN tbl_alertas ON tbl_usuarios.Nombre = tbl_alertas.Owner
WHERE (STATUS = 'On approve' OR STATUS = 'Active') AND DATE(CloseDate) < CURDATE()

Related

Where do I begin Looping statements in MySQL Workbench

I need to have this query run 12 times (previous 12 months) and append the results to a table. I am not very good with looping, looking for input. I am just not sure where to put my counter variables or any other looping statements. I think I may need two variables to loop because of the Previous Month First Day and Last day variables.
SET #PM_FD = last_day(curdate() - interval 2 month) + interval 1 day;
SET #PM_LD = last_day(curdate() - interval 1 month);
insert into sandbox.metrics_history
SELECT
'CHI' as Company
,count(*) as Result
,'SSRM10' as Metric_ID
,'PONoReqLine' as Metric_Name
, MONTHNAME(#PM_FD) as Month, year(#PM_FD) as Year
FROM
poline pol
INNER JOIN
purchorder po ON pol.company = po.company
AND pol.po_number = po.po_number
AND pol.po_release = po.po_release
AND pol.po_code = po.po_code
LEFT JOIN
polinesrc src ON pol.company = src.company
AND pol.po_number = src.po_number
AND pol.po_release = src.po_release
AND pol.line_nbr = src.line_nbr
AND pol.po_code = src.po_code
LEFT JOIN
buyer byr ON pol.buyer_code = byr.buyer_code
WHERE
pol.buyer_code != 'POC'
AND src.company IS NULL
AND po.po_date >= #PM_FD
AND po.po_date <= #PM_LD
ORDER BY pol.company , pol.po_number , pol.line_nbr

How to read from the two same dates without input the time

I have a query like below.
SELECT
occupation AS 'Contact occupation',
sum(total) AS 'Quantity'
FROM
(
SELECT
CASE
WHEN contacts.occupation IS NULL THEN 'Other'
WHEN trim(contacts.occupation) = '' THEN 'Other'
ELSE contacts.occupation
END AS occupation, count(DISTINCT(concat(patients.id, '-', individual_appointments.practitioner_id))) AS total
FROM
individual_appointments
JOIN patients ON
patients.id = individual_appointments.patient_id
JOIN practitioners ON
practitioners.id = individual_appointments.practitioner_id
JOIN businesses ON
businesses.id = individual_appointments.business_id
JOIN referral_sources ON
referral_sources.patient_id = individual_appointments.patient_id
JOIN referral_source_types ON
referral_source_types.id = referral_sources.referral_source_type_id
LEFT JOIN contacts ON
referral_sources.referring_contact_id = contacts.id
WHERE
patients.created_at BETWEEN '2018-05-22' AND '2018-05-22'
AND CONVERT(NVARCHAR(100), referral_source_types.name) = 'Contact' [[
AND {{practitioner}}]] [[
AND {{clinic}}]]
AND isnull(individual_appointments.cancelled_at, '') = ''
AND individual_appointments.did_not_arrive <> 1
GROUP BY
contacts.occupation ) marketing_referrers
GROUP BY
occupation,
marketing_referrers.total
ORDER BY
total DESC;
When I submit a date like the following patients.created_at BETWEEN '2018-05-22' AND '2018-05-22' it doesn't return anything but if I enter BETWEEN '2018-05-22' patients.created_at 'AND' 2018-05-23' it returns a value.
I think if I just input two of the same date without entering the time then the time will be 00:00:00 - 00:00:00.
How to read 00:00:00 - 23:59:59 when we input two of the same date without entering the time?
The date format in the table is filled as follows "Thursday, August 20, 2020, 9:49 AM" but it can be read if we just input the date, for example 2020-08-20.
Your help means a lot to me, thank you
if your data type is datetime then you can add:
WHERE patients.createdAt >= '2018-05-22' and patients.createdAt < '2018-05-23'
because 2018-05-22 = 2018-05-22 00:00:00
if you want to input only one date, then u can use this
WHERE patients.createdAt >= '2018-05-22 00:00:00'
AND patients.createdAt <= '2018-05-22 23:59:59'
or you can simply use this
WHERE patients.createdAt LIKE '2018-05-22%'
it will give you all of the row which has the value '2018-05-22' on it
Try using ...WHERE DATE(patients.created_at) = '2018-05-22'...

MySQL update query with average from last 1 year

I am trying to update values from another table by taking averages for the last 1 year values. the query i have written below is definitely wrong as AsOfDate has not been included in query for table b, but is indicative of what i am trying to do. Thanks in advance.
update MT_1YR_AVG_EXGRATE a
join (select avg(ExchangeRate) as ExchangeRate, CurrencyId from Currency_Exchange_Rate_Data
where BaseCurrencyId = "USD" group by CurrencyId) b
on b.CurrencyId = a.CurrencyId and b.AsOfDate <= a.AsOfDate and b.AsOfDate > date_sub(a.AsOfDate,interval 1 year)
set a.ExchangeRate = b.ExchangeRate
where a.ExchangeRate = null;
Solved:
update MT_1YR_AVG_EXGRATE c join (
select b.CurrencyId, b.AsOfDate, avg(a.ExchangeRate) as ExchangeRate from Currency_Exchange_Rate_Data a, MT_1YR_AVG_EXGRATE b
where a.BaseCurrencyId = "USD" and a.CurrencyId = b.CurrencyId and b.ExchangeRate is NULL
and a.AsOfDate <= b.AsOfDate and a.AsOfDate > date_sub(b.AsOfDate,interval 1 year)
group by b.CurrencyId, b.AsOfDate) d
on d.CurrencyId = c.CurrencyId and d.AsOfDate = c.AsOfDate
set c.ExchangeRate = cast(d.ExchangeRate as decimal(19,5))
where c.ExchangeRate is NULL;

Mysql exclude saturday where another value is equal to

Im having a little trouble coming to the correct syntax for my code to do what I want. Im summing up numbers of hour worked in a specific week by an employee, but I want to exclude certain days from my query. The employee can have worked for different clients, which are defined by a client_id.
Now the code below have a syntax error in the WHERE-statements inside the parantheses, and I know why, Ill just let them be there for the sake of explaining what I want to achieve in this case.
I appreciate any help you can give me.
Btw: I also tried AND( DAYOFWEEK(date) <> 7 AND client_id = '1' ) but this doesnt work either. I recon this is because my query return just a single line of result, and thus my above code doesnt do anything while the query is loop
SELECT
date,
client_id,
SUM(hours)-37.5 AS total,
SUM(lunch = 'yes') AS lunch
FROM
hours
WHERE
CONCAT(WEEK(date, 1)) = '25'
AND
CONCAT(YEAR(date)) = '2015'
AND
employee_id = '14'
AND ( DAYOFWEEK(date) <> 7 WHERE client_id = '1' )
AND ( DAYOFWEEK(date) <> 1 WHERE client_id = '2' )
AND
status = 'billed'
HAVING SUM(hours) > 37.5
You can use a bunch of logical not and and logical operators to build this logic:
SELECT
date,
client_id,
SUM(hours)-37.5 AS total,
SUM(lunch = 'yes') AS lunch
FROM
hours
WHERE
CONCAT(WEEK(date, 1)) = '25'
AND
CONCAT(YEAR(date)) = '2015'
AND
employee_id = '14'
AND NOT ( DAYOFWEEK(date) = 7 AND client_id = '1' )
AND NOT ( DAYOFWEEK(date) = 1 AND client_id = '2' )
AND
status = 'billed'
HAVING SUM(hours) > 37.5

SQL datetime less than NOW() returns invalid results

I am trying to run the following SQL statement
SELECT
P.team_id,
P.id,
M.id,
P.`end`,
UHT.user_id
FROM phase P
INNER JOIN module M
ON P.Module_id = M.id
JOIN user_has_team UHT
ON UHT.team_id = P.team_id
WHERE
M.module_type = 7 OR
M.module_type = 8 AND
P.end < NOW();
This result returns 180 rows. if i go to the bottom of these rows i get a result that looks like this:
'52', '130', '275', '2014-12-16 00:00:00', '49'
This is just 1 out of many.
First i thought "Hey maybe the server time is invalid"
But when i run SELECT NOW() i get the following result:
'2014-11-02 19:38:49'
So what could the problem be?
You need some more parenthesis because of operator precedence in SQL.
Try changing your WHERE clause from
WHERE M.module_type = 7 or M.module_type = 8 AND P.end < NOW();
to
WHERE (M.module_type = 7 or M.module_type = 8) AND P.end < NOW();
Look into operator precedence,your query is interpreted as:
WHERE (M.module_type = 7)
or
((M.module_type = 8)
AND P.end < NOW());
But you need
WHERE (M.module_type = 7 or M.module_type = 8) AND P.end < NOW();