date_format parsing not working - mysql

Why does my date comparison not work,
mostly returning either all dates or none
Select DATE_FORMAT(time,'%Y - %m - %d'),'2013 - 01 - 10'
FROM signature,files
WHERE files.id = signature.id and instruction like '%BM%'
AND DATE_FORMAT(time,'%Y-%m-%d') < date('2013-01-10') ;
doesn't return result. when I change to DATE_FORMAT(time,'%Y-%m-%d') < '2013-01-10' same and even this DATE_FORMAT(time,'%Y %m %d') didn't work

DATE_FORMAT function returns a string with character set and collation.I am not sure if you will get correct comparison using DATE_FORMAT function.
Select DATE(time),'2013 - 01 - 10'
FROM signature,files
WHERE files.id = signature.id and instruction like '%BM%'
AND Date(time) < Date('2013-01-10') ;
or use STR_TO_DATE function.
SELECT STR_TO_DATE('2013,05,01','%Y,%m,%d');

Related

Convert mySQL query to KNEX

I am converting series of queries to Knex syntax.
I am having problem with this query:
SELECT id,reviewed,log_reference,CONVERT(notification USING utf8),create_time,update_time,store,user_id
FROM store_failure_log
WHERE reviewed = 0
AND create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW();
More precisely this line:
SELECT id,reviewed,log_reference,CONVERT(notification USING utf8),create_time,update_time,store,user_id
I have this Knex in place:
knex('store_failure_log')
.select('id', 'reviewed', 'log_reference', 'CONVERT(notification USING utf8)', 'create_time', 'update_time', 'store', 'user_id').convert('notification USING utf8')
.where('reviewed', 0)
.where(knex.raw('create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()'))
that produces this sql query:
select `id`, `reviewed`, `log_reference`, `CONVERT(notification USING utf8)`, `create_time`, `update_time`, `store`, `user_id` from `store_failure_log` where `reviewed` = 0 and create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()
Problem is in the: Convert(notification USING utf8).
The query is not valid, since the Convert is in parentheses. How can I write it with the knex?
In general how do I include SQL function calls in the KNEX syntax?
You can use raw to include SQL function calls in your Knex query, like you've already done in your where:
knex('store_failure_log')
.select(knex.raw('id, reviewed, log_reference, CONVERT(notification USING utf8), create_time, update_time, store, user_id'))
.where('reviewed', 0)
.where(knex.raw('create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()'))
Here is fixed version of #Veve's answer with correct quoting of identifiers and knex.raw syntax:
knex('store_failure_log')
.select('id', 'reviewed', 'log_reference', knex.raw('CONVERT(?? USING utf8)', ['notification']), 'create_time', 'update_time', 'store', 'user_id')
.where('reviewed', 0)
.where(knex.raw('?? BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()', ['create_time']))
https://runkit.com/embed/lh2i1qif7obx

How to use between operator for 2 date input parameters in mysql?

My task is to get the records between 2fromdate and todate(given as a input parameters).
i am not able to use between operator for 2 input parameters...
My query as follows...
DELIMITER $$
CREATE DEFINER=`testrunner`#`%` PROCEDURE `usp_GetAllTranasactions`(pFromDate nvarchar(30),pToDate nvarchar(30),pstatus int)
BEGIN
select
ST.UserID,U.Username,
ST.SubscriptionID,
ST.DateOfSubscription,
SM.SubType,
SM.Details,
ST.Amount,
ST.EndDate,
ST.Status
from tr_t_subscriptiontransactions ST
Join tr_m_users U on U.UserID=ST.UserID
join tr_m_subscription SM on SM.SubscriptionID=ST.SubscriptionID
where **ST.DateOfSubscription between (pFromDate and pToDate) and ST.EndDate
between(pFromDate and pToDate) and ST.Status=pstatus;**
END if;
END
here i don't know how to use between parameters..plz help me..i want to retrive record between fromdate and todate..hope u understand..
Let us assume you want all transactions for the month of June 2014
In your user interface the parameter values are:
from_date = 2014-06-01
to_date = 2014-06-30
But you will evaluate against a transaction date & time. How do you ensure that absolutely every transactions on June 30 - right up to midnight - is included in the results?
Here is how: use 2014-07-01 instead of 2014-06-30, and here is what the query would look like - which does NOT use between!
SELECT
ST.UserID
, U.Username
, ST.SubscriptionID
, ST.DateOfSubscription
, SM.SubType
, SM.Details
, ST.Amount
, ST.EndDate
, ST.Status
FROM tr_t_subscriptiontransactions ST
JOIN tr_m_users U
ON U.UserID = ST.UserID
JOIN tr_m_subscription SM
ON SM.SubscriptionID = ST.SubscriptionID
WHERE (ST.DateOfSubscription >= pFromDate AND ST.DateOfSubscription < pToDate + 1)
AND (ST.EndDate >= pFromDate AND ST.EndDate < pToDate + 1)
AND ST.Status = pstatus
;
AVOID between for date ranges because it INCLUDES both the lower and upper boundary values.
... equivalent to the expression (min <= expr AND expr <= max)
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between
What this can lead to is an "anti-pattern" which look like this:
where dt_field between '2014-06-01 00:00:00' and '2014-06-30 23:59:59'
but there are time units smaller than one second, so that approach is imperfect. Don't attempt to overcome the deficiencies of between by adjusting the upper value this way. The simple and more accurate approach is to use >= and < adjusting the upper value by one whole time unit (usually the next day).

str to date mysql function default day

is it possible to default the day field when using the string to date function in MySQL ?
I am using this:
sample_date = cast(STR_TO_DATE(#sampl_date,'%Y%m') AS date)
the input values I am receiving are in the format of
201305
201203
etc
so the str_to_date function works fine in converting that but it shows the day as 00 which I would like to default all of them to 01.
I tried various forms of the str_to_date function but none worked.
sample_date = cast(STR_TO_DATE(#sampl_date,'%Y%m%01') AS date)
sample_date = cast(STR_TO_DATE(#sampl_date,'%Y%m-01') AS date)
You could use this:
cast(STR_TO_DATE(CONCAT(#sampl_date, '01'),'%Y%m%d') AS date)

SQL date logic to fetch the values

Need SQL logic
If i enter sys date as 15th it has to fetch the values from 1-15th.
if i enter date as following month 2nd it has to fetch from 15th to
2nd.
Example
Sys date April 15th - April 1 to April 15th date values needs to be fetch.
Sys date May 2nd - April 15th to May 2nd date values needs to be fetch.
Please suggest
So as a general methodology you'd need a function to return the day number in the month, and two case statements to each return a particular date as a boundary. Date arithmetic is used to convert the system date to the upper and lower boundaries required, so on Oracle you'd use Trunc(sysdate,'mm') and add_months(...,n) and add days on as integers.
Date functions are here: http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions001.htm
Can't help you with MySQL functions -- doubtless they're documented somewhere.
you'll end up with ...
date_col > case <function on sysdate>
when < 15 then <function for lower bound case 1>
when < 15 then <function for lower bound case 2>
end and
date_col < case <function on sysdate>
when < 15 then <function for upper bound case 1>
when < 15 then <function for upper bound case 2>
end and
I would recommend using DAYOFWEEK() and MONTH() functions to determine the start and end dates of the query.
SET #day = DAYOFMONTH(<date entered>)
SET #month = MONTH(<date entered>)
IF #month > MONTH(NOW()) AND #day = 2 THEN
SET #start_date = DATE_SUB(<date entered>, INTERVAL 1 MONTH) + INTERVAL 13 DAY
SET #end_date = <date entered>
ELSEIF #month = MONTH(NOW()) AND #day = 15 THEN
SET #start_date = DATE_SUB(<date entered>, INTERVAL 14 DAY)
SET #end_date = <date entered>
END IF;
SELECT * FROM myTable WHERE myDate BETWEEN #start_date AND #end_date

Assigning a value from another database and function - MySQL variable scope

I am using MySQL to make a report showing the number of hours billed for a particular date range and project. The complexity is that the date range is variable for each project (different start month and start day). This information is coming from a value in another database/table.
I have the following UDF in MySQL:
DELIMITER //
CREATE FUNCTION TimeLeft(startday INT, today INT) RETURNS INT
DETERMINISTIC
BEGIN
DECLARE s INT;
IF startday < today THEN SET s = 0;
ELSE SET s = 1;
END IF;
RETURN s;
END //
DELIMITER;
I use that function in the following query, which is supposed to take the value returned in the TimeLeft function to determine the values for the start month (month(curdate())-#xx) and start day (#yy) for each project to calculate the hours:
AND time_records.record_date >= concat('2012/', month(curdate())-#xx , '/' , #yy)
Here's how I am setting the values for #xx and #yy:
SET #xx = 0; #this is the value that we will use to manipulate the month for the date range
SET #yy = 0;
#yy:= SELECT start_day_of_month FROM dashboard.client; #this doesn't seem to work
SELECT #xx:= TimeLeft(#yy,dayofmonth(curdate()));
I am getting some issues:
#yy is not getting the value - possibly my syntax is wrong?
The variables are set at the top of the code, so they are not getting changed for each project as they should be (there should be a different #xx and #yy for each project since each one has a different start and end date).
Here's the full query:
#below is where I assign the variables
SET #xx = 0; #this is the value that we will use to manipulate the month for the date range
SET #yy = 0;
#yy:= SELECT start_day_of_month FROM dashboard.client; #this doesn't seem to work
SELECT #xx:= TimeLeft(#yy,dayofmonth(curdate()));
# below is the MySQL query that is meant to use the variables assigned above
SELECT X.expr1 AS 'Project Name', #monthly_hours - SUM(X.expr2) AS 'Hours Billed
FROM
(SELECT
projects.name AS expr1
, sum(time_records.value) AS expr2
FROM project_objects
INNER JOIN projects
ON projects.id = project_objects.project_id
INNER JOIN time_records
ON time_records.parent_id = project_objects.id
WHERE time_records.parent_type = 'Task'
AND time_records.record_date >= concat('2012/', month(curdate())-#xx , '/' , #yy)
AND time_records.record_date <= curdate()
GROUP BY projects.name
UNION
SELECT
projects.name AS expr1
, sum(time_records.value) as expr2
FROM projects
INNER JOIN time_records
ON projects.id = time_records.parent_id
WHERE time_records.parent_type = 'Project'
AND time_records.record_date >= concat('2012/', month(curdate())-#xx , '/' , #yy)
AND time_records.record_date <= curdate()
GROUP BY projects.name) X
GROUP BY X.expr1
I think there is some issue of where I am assigning the variables #xx and #yy. These should be done for each individual Project, so putting them up on the top is probably not the best idea. I'm also not sure if I am assigning the #yy value correctly. It's supposed to query the value of the field of a table that is in another database but it keeps throwing a syntax error on the #yy assignment to that field.
Assign value to #yy inside select:
SELECT #yy:= start_day_of_month FROM dashboard.client;