Trying and failing to get a date-sub function to work in a node-red function. MySQL db.
Without any date_sub, this works fine (in a function)-
var options = { hour12: false };
var nowtime = new Date().toLocaleString("en-GB", options);
msg.topic = `SELECT COUNT(*) AS rowcount FROM \`node-red\`.\`tag_reads\` WHERE \`datetime\` < "${nowtime}"`;
return msg;
With the date_sub part the query fails (with a count of zero even though there are valid records, the query works fine in a conventional jsp)
msg.topic = `SELECT COUNT(*) AS rowcount FROM \`node-red\`.\`tag_reads\` WHERE \`datetime\` > date_sub( "${nowtime}", INTERVAL 90 MINUTE) `;
I suspect it is syntax, escape codes etc. The resulting sql string appears to show that datetime (from the table) is not being interpreted as a string (just 'datetime' appears rather than the contents of datetime which are, for example, 10/6/2022, 11:18:43), but, if this was the case then the first select statement would not be working either.
Thoughts appreciated
Ralph
it looks like in this statement
WHERE \`datetime\` < "${nowtime}" mysql is converting the string to datetime for you.
MySQL has the ability to compare two different dates written as a string expression.
from How to do date comparisons in MySQL
However, in this statement, date_sub( "${nowtime}", date_sub wants the argument to be of type date.
Syntax
DATE_SUB(date, INTERVAL value interval)
from MySQL DATE_SUB() Function
Related
I am using DATE() function to calculate the difference between two dates in MySQL
value of SYSDATE() function is following
select SYSDATE();
2020-07-15 12:16:07.0
When I am using date from same month, it is giving correct result
select DATE(SYSDATE())- DATE('2020-07-13');
2
But when I am using date from last month it is giving difference as 86 instead of 16;
select DATE(SYSDATE())- DATE('2020-06-29');
86
Edit:
I am aware that we can use DATEDIFF() but I want to verify why DATE() function is giving results like this since we are already using this in code
MySQL doesn't support subtracting one date from another. The code
SELECT DATE '2020-07-15' - DATE '2020-06-29';
should hence result in an error, but MySQL silently converts this to this instead:
SELECT 20200715 - 20200629;
Seeing that you want to subtract two values, it assumes that you want to work with numbers. Dates are not numbers, but their internal representation yyyymmdd can be represented numerically. So, while CAST(DATE '2020-07-15 ' AS int) fails with a syntax error, as it should, MySQL is not consistent, when it comes to subtraction. It generates the numbers 20200715 and 20200629 and works with these.
I consider this a bug. MySQL should either raise an exception or return an INTERVAL when subtracting one DATE from another.
I am trying to grab all the records for the month. The string I have to query with is in this format 2019-01-12. The record I am querying for is a DateTime record so it has a format like this 2018-08-11 13:39:22.959330.
So I am trying to structure a query that would achieve this
Score.where('user_id = ? AND date_closed.strftime("%Y-%m) = ?', current_user.id, date)
Where date is the 2019-01-12 string. The above code produces the error
FUNCTION date_closed.strftime does not exist
I did google but was unable to locate something that achieved this. Most solutions involved searching inside a range of dates, I would really like to try to keep the search method the same.
You have the DATE_FORMAT function for that https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
DATE_FORMAT(date_closed, "%Y-%m")
EDIT: you'll have to also format the date you are passing to the query
You can use mysql data functionos YEAR and MONTH:
Score.where('user_id = ? AND YEAR(date_closed) = ? AND MONTH(date_closed) = ?', current_user.id, date.year, date.month)
I work for a gun club and we are trying to find the total number of targets shot at during a specific year. The table contains totals from years 2000-2018 and I am trying to write a query that will look at the string for the date of the shoot which is in a format like this 2010-06-13 00:00:00.000 I just care about the year so I created this query:
SELECT SUM(ShotAt) AS TotalTargets
FROM MemberShootsC
WHERE GunClubNumber = 210015 AND ShootDate LIKE '2007-%%-%% 00:00:00.000'
If I run the query up to the AND clause it works and returns a total. However, I get a null value if I highlight the whole thing. I have tried variations of the string as well. Such as this '2007%' and this '2007-- %'
Not sure what I am missing. Any help is appreciated.
Don't convert to string to query for a year, use YEAR() function instead:
SELECT SUM(ShotAt) AS TotalTargets
FROM MemberShootsC
WHERE GunClubNumber = 210015 AND YEAR(ShootDate)=2007 -- MySQL
You could also use a range query
SELECT SUM(ShotAt) AS TotalTargets
FROM MemberShootsC
WHERE GunClubNumber = 210015 AND ShootDate BETWEEN '2007-01-01' AND '2007-12-01 23:59:59.999'
Note: The above assumes that you do not store dates as strings. The function to use depends on RDBMS. In MS SQL Server you would use DATEPART(year, ShootDate) = 2007
I ran this query in DBeaver
SELECT DLY.badge_nbr,
DLY.DIM_DT_ID,attribute_type
FROM FACT_MDM_DAILY_INT DLY
WHERE SCENARIO_TYPE = 'VOLTAGE'
AND ATTRIBUTE_TYPE = 'Phase_A_Average_RMS_Voltage'
AND DLY.dim_dt_id >= TO_DATE('2016-01-28','yyyy-mm-dd');
I get the error as QUERY [VIRTUAL] [ERROR]. Interestingly when I run the same query without date comparison in WHERE clause it works fine.
SELECT DLY.badge_nbr,
DLY.DIM_DT_ID,attribute_type
FROM FACT_MDM_DAILY_INT DLY
WHERE SCENARIO_TYPE = 'VOLTAGE'
AND ATTRIBUTE_TYPE = 'Phase_A_Average_RMS_Voltage';
The to_date() function in Denodo must have at least 2 parameters:
The date format of your string field (look at java SimpleDateFormat)
The string you want to convert to a date.
Thus, your parameters appear to be transposed, and you must use a capital M for month... since lower case m means minutes.
to_date('yyyy-MM-dd','2016-01-28')
I am wanting to show current month data. But when I am using this query, then generating extra single string from query.
$queryCurentMonth = $this->Bookings->find('all')
->where(["MONTH(Bookings.created)" => "MONTH(CURRENT_DATE())"]);
Generating :
SELECT
*
FROM
`bookings` `Bookings`
WHERE
MONTH(`Bookings`.`created`) = 'MONTH(CURRENT_DATE())'
This = 'MONTH(CURRENT_DATE())' , it is generating blank data. How we can perfect this query.
MySQL is treating your RHS value as string in
MONTH(`Bookings`.`created`) = 'MONTH(CURRENT_DATE())'
'MONTH(CURRENT_DATE())' shouldn't have single quotes around it. Instead it should be like this
MONTH(`Bookings`.`created`) = MONTH(CURRENT_DATE())
Try to compare year also as function MONTH() returns only a number 1 through 12, the query would return all records for a Month of all years, rather than only the current year. Use both MONTH(), YEAR() to compare months for the current year.
MONTH(`Bookings`.`created`) = MONTH(CURDATE()) AND YEAR(`Bookings`.`created`) = YEAR(CURDATE())
Finally, I have got a solution. it is working finely now.
$queryCurentMonth = $this->Bookings->find('all')
->where(["MONTH(Bookings.created)" => date("m")]);