MySQL - Find date ranges matching a list of months - mysql

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

Related

I want to find the previous month's date for specific date in SQL

I want to get the previous month date for specific dates in SQL. For example: 6.21.19 has a previous month date of 5.21.19.
I am just trying to get comps from this.
MONTH( curdate() ) -1
I need to return the previous month date.
Welcome to the board Arie. Judging from your question and responses, you need a range of dates and their prior month relations. The easiest way would be for all of the dates you need to look up to be in a table, then the answers provided so far would work. Since that doesn't appear to be the case, I'm guessing you are creating date ranges on the fly.
So lets assume you need exactly the data shown in your example, there are two parts to this, first you need to get a list of days that you want to look up, then you need to get the day in the prior month. There are lots of ways to get a sequence of days, but for simplicity I'll use a recursive CTE. Once I have the date range, I'll just select the dates and their prior month date as well.
with Date_CTE as (select cast('6/1/2019' as datetime) as repDate
union all
select dateadd(day, 1, repdate) as repDate
from Date_CTE
where repDate < '06/07/2019')
select repDate, dateadd(month, -1, repDate) as PriorDate
from Date_CTE
CTEs are helpful functions and you can get more details on them here, but it's worth noting there are many ways to do this. Hope this gets you pointed in the right direction.
SELECT yourDateColumn, yourDateColumn-interval 1 month as prevMonthDate

Sql search Result between two dates

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.

mysql get data from a specific week [duplicate]

I am having a table as follows in MYSQL:
proj_id|hoursWorked|Date.
The date field is of type Date; I want to retrieve all the entries from a table depending on a given week number for the project in my java based web application. Please help me to achieve this.
I am unable to write a single query that will allow me to do so.
Do not use something like WHERE WEEK(column)=something - this is a performance killer: It will calculate the week number on all rows, even if they don't match. In addition to that it will make it impossible to use an index ont this column.
Instead calculate an absolute begin and end date or point in time, depending on your data type, then use BETWEEN. This will do no calculations on non-matching rows and allow the use of an index.
Rule of thumb: If you have the choice between a calculation on a constant and on a field, use the former.
use MySQL WEEK() function.
SELECT WEEK(dateColumn)
FROM...
WHERE WEEK(dateColumn) = 1
WEEK()
from MySQL Docs
This function returns the week number for date. The two-argument form
of WEEK() enables you to specify whether the week starts on Sunday or
Monday and whether the return value should be in the range from 0 to
53 or from 1 to 53.
Use WEEK
select * from your_table
where week(`Date`) = week('2012-12-01')
If you want to get only records from the current week you can do
select * from your_table
where week(`Date`) = week(curdate())

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)

Getting week started date using MySQL

If I have MySQL query like this, summing word frequencies per week:
SELECT
SUM(`city`),
SUM(`officers`),
SUM(`uk`),
SUM(`wednesday`),
DATE_FORMAT(`dateTime`, '%d/%m/%Y')
FROM myTable
WHERE dateTime BETWEEN '2011-09-28 18:00:00' AND '2011-10-29 18:59:00'
GROUP BY WEEK(dateTime)
The results given by MySQL take the first value of column dateTime, in this case 28/09/2011 which happens to be a Saturday.
Is it possible to adjust the query in MySQL to show the date upon which the week commences, even if there is no data available, so that for the above, 2011-09-28 would be replaced with 2011/09/26 instead? That is, the date of the start of the week, being a Monday. Or would it be better to adjust the dates programmatically after the query has run?
The dateTime column is in format 2011/10/02 12:05:00
It is possible to do it in SQL but it would be better to do it in your program code as it would be more efficient and easier. Also, while MySQL accepts your query, it doesn't quite make sense - you have DATE_FORMAT(dateTime, '%d/%m/%Y') in select's field list while you group by WEEK(dateTime). This means that the DB engine has to select random date from current group (week) for each row. Ie consider you have records for 27.09.2011, 28.09.2011 and 29.09.2011 - they all fall onto same week, so in the final resultset only one row is generated for those three records. Now which date out of those three should be picked for the DATE_FORMAT() call? Answer would be somewhat simpler if there is ORDER BY in the query but it still doesn't quite make sense to use fields/expressions in the field list which aren't in GROUP BY or which aren't aggregates. You should really return the week number in the select list (instead of DATE_FORMAT call) and then in your code calculate the start and end dates from it.