this is my first question here, thanks for your support.
I have an old database with many columns, but the is not a DATE column. Yes, my mistake.
But, I have a column called question_id with some data, that contains the date and time, like
2017113020440370769
where first 4 digits are YYYY, next 2 digits are MM and next 2 are DD.
I´m trying to make a query extracting those characters to count how many questions I had on specific dates.
I could, doing this for a specific date:
SELECT COUNT(*)
FROM questions
WHERE question_id LIKE '20171228%';
But I want to automatize this for TODAY, everyday, not typing each day the YYYYMMDD%
Is it possible? Using CURDATE? Or there is any specific TIMESTAMP I can use?
Thank you very much!
Yes it is possible, you can build the current dates with wild card as below:
SELECT COUNT(*)
FROM questions
WHERE question_id LIKE CONCAT(DATE_FORMAT(CURDATE(), '%Y%m%d'), '%');
That's for a specific day; today. For all dates you would have to do an aggregation on the date part of the question_id as illustrated below:
SELECT SUBSTR(question_id,1,8) ASKED_ON, COUNT(*) NUMBER_OF_QUESTIONS
FROM questions
GROUP BY SUBSTR(question_id,1,8);
You can get today's date with e.g. CURDATE()
You can format dates with DATE_FORMAT()
You con concatenate strings with CONCAT()
Those are all the bricks you need ;-)
Try this:
SELECT LEFT('20171228ASD',8) = CURRENT_DATE();
SELECT COUNT(*)
FROM questions
WHERE LEFT(question_id',8) = CURRENT_DATE();
Related
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.
I have attendance data for employees stored in the table attendance with the following column names:
emp_id (employee ID)
date
type (leave, absent, etc.)
(there are others but I'm omitting them for the sake of simplicity)
My objective is to retrieve all dates of the given month on which the employee was on leave (type = 'Leave') and the last leave taken in the last month, if any.
It's easy to do it using two queries (I'm using PHP to get process the data), but is there any way this can be done in a single query?
I'm answering my own question so as to close it. As #bpgergo pointed out in the comments, UNION will do the trick here.
SELECT * FROM table_name
WHERE type="Leave" AND
date <= (CURRENT_DATE() - 30)
Select the fields, etc you want then se a combined where clause using mysql's CURRENT_DATE() function. I subtracted 30 for 30 days in a month.
If date is a date column, this will return everyone who left 1 month or longer ago.
Edit:
If you want a specific date, change the 2nd month like this:
date <= (date_number - 30)
I got a table called calendar, in that table I have this rows:
-day
-month
-year
why? Because I need it hehe.
So, the problem is when I want search a date in diferent year ( in the same year it's ok), for example:
Days between: 31-12-2013 and 1-1-2014, so I have a query:
SELECT * FROM calendar WHERE concat(year,'-',month,'-',day) BETWEEN '2013-1-30' AND '2013-1-31';
But, this query search in the same year and show the another months (I have in my db the 730 days) and not the 2014.
So, I'm confused because, how can I concat the rows and search with between?
Hope you can help me to understand, and sorry for my english.
Thanks for all.!!
Use str_to_date:
SELECT * FROM calendar
WHERE str_to_date(concat(year,'-',month,'-',day),'%Y-%m-%d')
BETWEEN '2013-1-30' AND '2013-1-31';
sqlfiddle demo
Try
SELECT * FROM calendar WHERE DATE(CONCAT(year,'-',month,'-',day)) BETWEEN '2013-1-30' AND '2013-1-31';
I'm also curious as to why you 'need' to store year, month and day as three seperate fields, and not in a single date field?
I think year, month and day may also be reserved keywords in mysql, so you may have to do
SELECT * FROM `calendar` WHERE DATE(CONCAT(`year`,'-',`month`,'-',`day`)) BETWEEN '2013-1-30' AND '2013-1-31';
I have this problem if anyone can help.
There is a field (date) in my table (table1) that is a date in the format 3/31/1988 (M/D/y), and my necessity is to define how many days have passed since that date.
I have tried to give this instruction
SELECT DATEDIFF(CURDATE(), date) AS days
FROM table1
But it gives back 'null' and I think this happens because the two date formats are different (CURDATE() is YMD.....
Is it correct? can anyone help me?
Thank you in advance
You can use STR_TO_DATE():
SELECT DATEDIFF(CURDATE(),STR_TO_DATE(date, '%m/%d/%Y')) AS days
FROM table1
SQLFiddle Demo
Your DATE field should have DATE or DATETIME format to be used as DATEDIFF argument correctly.
Also DATE is MySQL keyword and I am not sure that you can use it as valid field name.
You can use this for accurate result
SELECT DATEDIFF(CURDATE(), DATE_FORMAT(FROM_UNIXTIME(UNIX_TIMESTAMP(`date`)), '%Y-%m-%d')) AS days FROM `table1`
If you want to consider results without - signs that you have to follow parameters position as below :
SELECT DATEDIFF(Big_Date,Small_Date) AS days FROM table1.
positive results e.g 5 (with no sign), if you place a Small date as the first parameter then it will results minus sign e.g -5.
I have a mysql database that looks like this:
id | userid | timestamp | activity
Timestamp is a datetime data type, I need to get the data grouped by month, day and hour. I am using mysql and php for my scripts.
I am able to do it by month and day with the following query:
$query = "SELECT COUNT(id) as totals FROM security_transactions WHERE YEAR(timestamp) = 2012 GROUP BY MONTH(timestamp), DAY(timestamp)";
I need to do it by month day and hours.
Please help.
Thanks.
You can add , HOUR(TIME(timestamp)) to your group by query providing your column is of DATETIME format
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_hour
Also, from the error messages put in the comments below, it looks like #Aprentice is not using mysql, but I've improved this answer for others looking for mysql.
I have never used mssql, so I can't test this but the following might work to group by nearest hour:
GROUP BY dateadd(hour, datediff(hour, 0, timestamp, 0)
Just take it one step further and use HOUR() as well. You will first need to extract the time portion of the timestamp. But guess what, there is a function for that as well ;)