Sql search Result between two dates - mysql

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.

Related

MySQL Query Group By Date

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.

Select leave data from attendance table given the following condition

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)

MySQL: Modifying output of a field for calculation

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.

mysql date direct subtraction

I have a two date columns, dateA and dateB. If I subtract dateA from dateB (dateB - dateA), I get wrong results but not using DATEDIFF(dateB,dateA)function. I get wrong result from direct subtraction when used in a table with data but not with below query.
SELECT DATE('2013-01-31') - DATE('2013-01-27')
Why?
EDIT:
I found that in MySQL if the two dates are within a month then direct subtraction gives correct result but if the dates span month, year there might be a problem.
Am I right?
Presumably, you columns are not stored as dates, but as strings. If they were stored as dates, then subtraction would work as expected.
When you subtract two strings, such as:
SELECT '2013-01-31' - '2013-01-27'
Then MySQL converts them to numbers, based on the leading digits. In this case, both start with the numbers 2013, so both are converted to 2013 (if there were no digits at the beginning then the value would be 0). These numbers are then subtracted.
Are your column's defined as date, or as Varchars? Because Date as a String means nothing. When you do a DATE('2013-01-31'), it creates a date object and hence the subtraction works. So, if your column is defined as Varchar, do DATE(dateB) - DATE(dateA).

MySQL - Find date ranges matching a list of months

I have several rows in a table, each containing a start date and an end date. The user has a checkbox for each month of the year. I need to determine which rows contain a date range that includes any of the user's chosen months.
It's easy to check the start & end months by, for example, MONTH(start_date) IN ($month_list), but this approach won't match any months between the two dates.
So I suppose what I'm asking is: is there a way of obtaining the inclusive months from a date range purely in SQL?
I assume you would want to include data rows where the date range spans or intersects with the selected periods - in which case, I'd shove the user selected periods into a table and do a fuzzy join, something like.....
SELECT DISTINCT at.*
FROM a_table at, user_periods up
WHERE at.start_date<=up.end_date
AND at.end_date>=up.start_date
AND up.trans_id=$SOME_VAR
(the trans_id just allows the table to be used for multiple operations)
To minimise the effort here, the user_periods table should have an index on start_date and end_date, and similar for a_table.
Can something like this help?
WHERE
MONTH(start_date) < MONTH_YOU_ARE_CHECKING and
MONTH() > MONTH_YOU_ARE_CHECKING
If you need to check all at once you can do a list of all the months and after delete from the list the month that the user choose, and after compare against the list. It will be better with a pseudocode example :)
MONTHS = 1,2,3,4,5,6,7,8,9,10,11,12
USER_SELECTED_MONTHS= 1,6,8,9,12
LIST_TO CHECK = 2,3,4,5,7,10,11
so, now you can do:
MONTH(start_date) NOT IN (2,3,4,5,7,10,11)
What do you think, could it help you?
regards