I have tried various recommendations based off of other posts with no avail.
I have a database scheme of records with a Created_Date Key, and Value would be 01/01/2017
I am trying to query the database records to give a returned count of How many records per month and which month those fall in line with.
With the following
SELECT SQL_NO_CACHE MONTH(`Created_Date`), COUNT(*)
FROM `CRM_Leads`
GROUP BY MONTH(`Created_Date`)
I return
MONTH(`Created_Date`) COUNT(*)
NULL 872
I have also tried almost all the variations on the following post
Count records for every month in a year
Any help would be appreciated.
assuming your created_date is a string of format ('dd-mm-yyyy') the you should convert as date with str_to_date
SELECT SQL_NO_CACHE MONTH(str_to_date(`Created_Date`, '%d/%m/%Y')), COUNT(*)
FROM `CRM_Leads`
GROUP BY MONTH(str_to_date(`Created_Date`, '%d/%m/%Y'))
For as long as you store date/time information as strings, you will have great difficulty using any date/time specific functions and features. If you are getting NULL from MONTH(str_to_date(Created_Date, '%d/%m/%Y')) then the str_to_date isn't converting the strings to dates and the most likely reason for this is the d m y "pattern" is not corrrect.
All you have old us about your "strings that might be dates" is that one of them looks like this: 01/01/2017. Now that could be DD/MM/YYYY or MM/DD/YYYY and we simply cannot tell which one is correct from the single value you have chosen to share with us. Look for any day value greater then 12 in your data e.g. 17/01/2017 ==> DD/MM/YYYY or 01/17/2017 ==> MM/DD/YYYY
Once you have made the choice of which pattern your "strings that might be dates" follow; apply that pattern in the str_to_date() function. You migh want to try a few different patterns to get the best one (and these are just 3 of many you could try):
# which pattern is best for you?
SELECT Created_Date
, str_to_date(`Created_Date`, '%d/%m/%Y') "d/m/y"
, str_to_date(`Created_Date`, '%m/%d/%Y') "m/d/y"
, str_to_date(`Created_Date`, '%Y-%m-%d') "y-m-d"
FROM `CRM_Leads`
You will not have success with your group by query until you choose the most appropriate d m y pattern to apply in teh str_to_date function. Note here that you might also have a variety of patterns in your data, in which case you have an even bigger problem to solve.
Once you have made the choice of which pattern your "strings that might be dates" follow; apply that pattern in the str_to_date() function and ONLY THEN your group by query will work.
Related
In my database table, there is a date column i.e. EXPECTED DATE which is in dd-mm-yyyy format, and the datatype of the column is text. Now, I want to convert the format to yyyy-mm-dd. But the date is not changing at all and also when I tried to get the timestamp for the expected date column . I am getting some errors. For date coming I have used this STR_TO_DATE. But the year is not coming like what I expect and the timestamp also.
For example:
select STR_TO_DATE ('30-11-2011', '%d,%m,%y') as date ;
returns a result as
2020-11-30
And for timestamp
select STR_TO_DATE ('2011,11,30 12,30,45', '%y,%m,%d, %H,%I,%S');
I am not getting errors.
Please help me get the correct answers for this problem.
For the first query you need to use the %Y. Remember that it is always better to use "Y" for the years when you are writing a query for year.
SELECT STR_TO_DATE("30,11,2011", "%d,%m,%Y");
For the second one also, you can use '%Y' in the place of '%y'. For minutes, use '%i' not '%I'. For hours and minutes, you can use whatever you like.
SELECT STR_TO_DATE("2011,11,30 12,30,45", "%Y,%m,%d %h,%i,%s");
Refer to the below documentation for more clarification on SQL commands.
You need %Y (capital Y) for the 4 digit year, when using MySQL's STR_TO_DATE. Also, minutes is represented by %i, not %I, the latter which is hours on a 0 to 12 scale. So use:
SELECT STR_TO_DATE('30-11-2011', '%d-%m-%Y');
SELECT STR_TO_DATE('2011,11,30 12,30,45', '%Y,%m,%d %H,%i,%S');
For the first query you need to use the %Y'.
SELECT STR_TO_DATE("30,11,2011", "%d,%m,%Y");
For minutes, use this one only '%i'.
SELECT STR_TO_DATE("2011,11,30 12,30,45", "%Y,%m,%d %h,%i,%s");
I'm trying to run a query that, given a product, his estimated duration and the date when the product was received returns the expiration date and the days until that expiration date. I already have another query doing exactly the same but using another table and it works fine, but for some reason with this one, I can't make it work and keep receiving the error "This expression is typed incorrectly, or it is too complex to be evaluated.". I've read a lot of answers here and tried various different things (check if I have null values, if all dates are typed correctly, using DateValue, ...) but none of them seems to work.
Can anybody help me?
The code I'm using is:
SELECT DISTINCT QueryMensalMov.PersonID, QueryMensalMov.[Nº pessoal] AS [Name], QueryMensalMov.Product, QueryMensalMov.Quantity, [ProductList].DurationDays, QueryMensalMov.Date, DateAdd("d",Nz([ProductList].[DurationDays],0),DateValue([Date])) AS ExpirationDate, DateDiff("d",Date(),DateAdd("d",Nz([ProductList].[DurationDays],0),Date)) AS Days
FROM [ProductList] INNER JOIN QueryMensalMov ON [ProductList].ProductID = QueryMensalMov.ProductID
WHERE ((([ProductList].DurationDays)>0) AND ((DateAdd("d",Nz([ProductList].[DurationDays],0),Date)) Between Date() And (Date()+90)));
The tables are:
QueryMensalMov
PersonID
Nº pessoal
ProductID
Date
1
Filipa
A
20-05-2020
2
Mark
B
15-07-2021
Product List:
ProductID
DurationDays
A
30
B
90
Thank you so much for your help!
Try to use [Date]:
SELECT DISTINCT
QueryMensalMov.PersonID,
QueryMensalMov.[Nº pessoal] AS [Name],
QueryMensalMov.Product,
QueryMensalMov.Quantity,
[ProductList].DurationDays,
QueryMensalMov.Date,
DateAdd("d", Nz([ProductList].[DurationDays],0),DateValue([Date])) AS ExpirationDate,
DateDiff("d", Date(), DateAdd("d", Nz([ProductList].[DurationDays],0), [Date])) AS Days
FROM
[ProductList]
INNER JOIN
QueryMensalMov
ON [ProductList].ProductID = QueryMensalMov.ProductID
WHERE
([ProductList].DurationDays > 0)
AND
(DateAdd("d", Nz([ProductList].[DurationDays],0),[Date]) Between Date() And (Date()+90));
Ok already fixed it, to be honest it was a stupid mistake.
The table QueryMensalMov is actually a Query based in another table. The problem was that the field Date was in Date/Time Extended format, instead of just Date/Time. That was causing the problem as, obviously, he couldn't execute the DateAdd with that kind of Date.
Don't know if this may be useful to someone, because this was a stupid mistake, but here it is. Always check the formats of your tables!
i have a table name expected expense in which i have 4 columns name Expense_title, Amount, expense_category, date and all the 4 columns have var char type. When I try to find expense between two dates it work fine for same year, e.g. 11/27/2018 and 12/27/2018, but it doesn't get any result when I try to find expense between two years, e.g. 12/27/2018 And 01/27/2019. please help
I am trying this query
SELECT *
from expected_expense
WHERE Date BETWEEN '$start_date' AND '$end_date'
As per the comments, this is because of the varchar type.
The between operator is nothing different than doing two closed inequalities for its range limits. In your example,
between 12/27/2018 And 01/27/2019
will be changed internally to
>= 12/27/2018 and <= 01/27/2019
but these are not dates, they are text. And the second one is less than the first, so nothing will be returned. It's like asking the question: which letter comes after q but before b? None.
Either change the fields to datetime, or use conversion functions in your query.
SELECT * FROM table WHERE '2016-03-31' > (SELECT MAX(year) from table where bill_id = 'somevalue')
I am using above query to check if 2016-03-31 is greater than all years present in table against bill_id. It is working fine. but is it correct approach to compare dates. dates will always in above format. Is there any need to convert date format for comparison. value 2016-03-31 will change dynamically but it will be always in Y-m-d format
Note : year is column name which contains full date in Y-m-d format like 2016-05-20
You are not comparing dates. You are comparing a string '2016-03-31' with a number, e.g. 2015.
In order to compare, MySQL silently converts the string to number. One would expect this to crash, as '2016-03-31' certainly isn't a number. MySQL, however, reads from left to right and takes from there all that can be considered a number, i.e. '2016'. Well, one could argue that some people put a minus sign at the end of a number, so this should be '2016-', i.e. -2016. Anyway, MySQL stops before the minus sign, gets 2016 and uses this for the comparision.
I don't know if all this is guaranteed to work in the future. I would not rely on this.
What result would you expect anyway? Is the 31st of March 2016 greater than the year 2016? That's a queer question, don't you think?
Try this. But do you really have a column year that stores only year?
SELECT * FROM table WHERE year(STR_TO_DATE('2016-03-31'))
> (SELECT MAX(year) from table where bill_id = 'somevalue')
SELECT * FROM table WHERE YEAR('2016-03-31') > (SELECT MAX(year) from table where bill_id = 'somevalue')
MySQL YEAR() returns the year for a given date or timestamp. The return value is in the range of 1000 to 9999 or 0 for 'zero' date.
I know calculating age from DOB is relatively simple but I have an issue with different data entry formats in the database. Also, I know this can be easier using PHP, but I don't know PHP and only have MySQL to work with.
The DOB entered into the DB is entered as "month/day/year" or "00/00/0000". But when calculating against today's date, the date would be formatted as "year-month-day" or "0000-00-00". Furthermore, the month placed in the DOB field can have either a one number month (1/01/1999) or a two number month (01/01/1999), so it's not consistent.
I am trying to use the below to utilize CONCAT, SUBSTRING and LOCATE to output the DOB in a better suited format for the age calculation. I think I'm close but not quite there. Any help would be very much appreciated.
SELECT
CONCAT(SUBSTRING(APPU_DOB,-4,4),'-', SUBSTRING(APPU_DOB,LOCATE('/', APPU_DOB),1),'-',SUBSTRING(APPU_DOB,4,2))
FROM APPU_APP_USER
JOIN APPL_APP ON APPU_APPL_ID = APPL_ID
WHERE DATE_FORMAT(APPL_CREATE_DT, '%Y-%M-%D') >= '2014-01-01';
Instead of Concat use str_to_date function.
select str_to_date( appu_dob, '%m/%d/%Y' ) as 'dob';
on 1/01/1999 it returns a valid date formatted object with value 1999-01-01.
You can use it on other date strings that have single or two digit day or month numbers.
Note: To represent or refer a month, use small case m but not capital M, in the format pattern string.
And you should better redefine the data type of appu_dob field to date. So that you can easily apply date specific functions on it for any calculations.