Show week beginning date with week() - mysql

I am using the week function like so:
SELECT
sub.id AS ARID,
WEEK(my.data) AS Week,
Is it possible to add the week beginning date that the week corresponds to?
Something like:
SELECT
sub.id AS ARID,
WEEK(my.data) AS Week,
MIN(my.data) AS WKBeginning
Using MIN in this way I remove a lot of data unintentionally - it should be divorced fromt he data even. Put another way, I'd like to display Week as a date rather than a number that is along the lines 'Monday-2014-09-04'
Is that possible?

My first answer turned out to be incorrect if the source table didn't include the full range of dates for the week (specifically the first day of the week).
The correct way is to use ADDDATE():
ADDDATE(my.data, INTERVAL 1-DAYOFWEEK(my.data) DAY) AS CorrectWKBeginning,
A correlated sub-query should does not work when the first day of the week is not included in the data:
SELECT
id,
WEEK(d) AS Week,
ADDDATE(d, INTERVAL 1-DAYOFWEEK(d) DAY) AS CorrectWKBeginning,
(SELECT MIN(d) FROM t WHERE WEEK(d) = WEEK(t2.d)) as IncorrectWKBeginning
FROM t t2
Sample SQL Fiddle
You might have to use week() with parameters to set the start day of the week and if it counts from 0-53 or 1-53, see the MySQL manual for reference.

Related

MySQL Date For Monthly Reporting

I need some help with running a query at month end. Each 1st working day of a month may differ, and therefore I may only be at work on the 3rd of a given month.
I am trying to figure out what my WHERE statement would look like to select data for the current month, unless it is:
1st of a month, then it will need to select everything from the previous month
1st working day of a month, which could be the 3rd. It will then also need to select the previous month's data.
These are two scenarios I am currently playing with, and don't have data to test it with as yet.
I have thought about doing
WHERE
MONTH(action_date) = MONTH(DATE_SUB(CURDATE(),INTERVAL 1 DAY))
But this then also returns data from 2016.
I have also thought of doing
WHERE
action_date = DATE_SUB(CURDATE(),INTERVAL 1 DAY)
But this would not work if today was say Monday the 3rd.
I would appreciate any answers that would give me the best way of doing this
You could simply subtract a few more days or even a month from the date, as all you will actually get from the subtraction is a month anyway
MONTH(DATE_SUB(CURDATE(),INTERVAL 5 DAY))
OR
MONTH(DATE_SUB(CURDATE(),INTERVAL 1 MONTH))

Find data of a whole month in sql

I have this query where I provide to-date & from date.
SELECT *
FROM sales
WHERE date between to-date AND from-date;
Now I want to execute this query with following parameters
to-date = Oct-2015
some-other-date = Oct-2015
That is I want records of the whole month.
How would I do that in a query where I have to and from dates provided it will work for both scenarios where months can be same and different as well.
Update:
dataType for column date is date
You can find the first day of the month containing any given timestamp with an expression like this. For example by using the timestamp NOW(), this finds the first day of the present month.
(DATE(NOW() - INTERVAL DAYOFMONTH(DATE(NOW()))
That's handy, because then you can use an expression like
(DATE(NOW() - INTERVAL DAYOFMONTH(DATE(NOW())) - INTERVAL 1 MONTH
to find the beginning of the previous month if you like. All sorts of date arithmetic become available.
Therefore, you can use an expression like the following to find all records with item_date in the month before the present month.
WHERE item_date>=(DATE(NOW()-INTERVAL DAYOFMONTH(DATE(NOW()))- INTERVAL 1 MONTH
AND item_date < (DATE(NOW()-INTERVAL DAYOFMONTH(DATE(NOW()))
Notice that we cast the end of a range of time as an inequality (<) to the moment just after then end of the range of time.
You may find this writeup useful. http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/
It's often useful to create a stored function called TRUNC_MONTH() to perform the conversion of the arbitrary timestamp to the first day of the month. It makes your SQL statements easier to read.
select * from sales
where from-date >= 1-Oct-2015
and to-date <= 1-Nov-2015
Update
select * from sales
where date >= from-date
and date <= to-date
Here is SQLFIDDLE
You Can get month from your both to and from dates and find records of that month
SELECT * FROM sales
WHERE MONTH('2002-01-03') AND MONTH('2002-01-3')
SqlFiddle of Using Month Function

Selecting 'DATE' fields in mysql by month and day with comparison

Trying to select a closest previous and next holiday from the database. Say, New Year's Day is always at the 1st of January, and New Year's Eve is at the 31st of December. Current year is completely irrelevant, so I'm trying to select previous holiday by day and month (New Year's Eve) with the following MySQL query:
SELECT * FROM `calendar` WHERE DATE_FORMAT(`holidayDate`, "%m-%d") < "01-01"
It gives NULL. I was expecting that it would drop through and will look in the previous month, December, but...
Tried a lot of different ways of doing it, but still no success.
P.S.: Cannot use TIMESTAMP in this case...
The reason it's returning null is because there isn't anything less than '01-01'. The query doesn't wrap around to the beginning.
What I would do is write a case statement that checks to see if you are at the earliest holiday.
If you are the earliest holiday, then you can select the latest holiday (a way of wrapping around).
If you are not the earliest holiday, then you need to select the one before it. I did this by ordering them in descending date, and limiting it to 1. (Effectively grabbing the holiday occurring before the current date.)
Try this:
SELECT *
FROM calendar
WHERE
CASE WHEN DATE_FORMAT(CURDATE(), '%m-%d') = DATE_FORMAT((SELECT MIN(c.holidayDate) FROM calendar c), '%m-%d')
THEN holidayDate = (SELECT MAX(c.holidayDate) FROM calendar c)
ELSE
DATE_FORMAT(holidayDate, '%m-%d') < DATE_FORMAT(CURDATE(), '%m-%d')
END
ORDER BY holidayDate DESC
LIMIT 1;
Here is an SQL Fiddle example. I created two queries. One that uses the current date (seen above) and one that has Jan 1st hard coded to show that the case statement does work. I've only added certain holidays to test.
If two queries are acceptable for you:
SELECT max(holidayDate) as prev_holiday from calendar where holidayDate < now();
SELECT min(holidayDate) as next_holiday from calendar where holidayDate > now();

Fetch mysql data of timstamp depending on time given

I have a column with timestamp, contain example value "2014-04-16 18:00:00","2014-04-17 18:00:00"....
Now, if I will call a page before "2014-04-17 12:00:00" I need this value-"2014-04-16 18:00:00"
And if I call my page after "2014-04-17 12:00:00" I need this value "2014-04-17 18:00:00".
I think my question is very complicated to understand, having complications in date & times, please check date & time properly.
I want to fetch this data from DB in mysql, The page I was saying is that where I'm going to add your mysql query.
Thanx in advance
Generalising what your asking for a bit the following will return dates from the previous day if it's before noon and dates from today if it's after noon:
SELECT date_column
FROM yourTable
WHERE DATE(DATE_SUB(NOW(), INTERVAL 12 HOUR)) = DATE(date_column);
Edit:
The WHERE clause First gets the current time (NOW()) and subtracts 12 hours. This wont affect the date unless the time is before 12. This means DATE_SUB(NOW(), INTERVAL 12 HOUR) gives us today if it's after noon and yesterday if it's before.
We then check if the date_column matches the date we've created (using the DATE function so that the time is ignored).
Adding some rows to the SELECT may help you see how these dates are built up.

How do I select two weeks ago in MYSQL?

I have a report that is driven by a sql query that looks like this:
SELECT batch_log.userid,
batches.operation_id,
SUM(TIME_TO_SEC(ramses.batch_log.time_elapsed)),
SUM(ramses.tasks.estimated_nonrecurring + ramses.tasks.estimated_recurring),
DATE(start_time)
FROM batch_log
JOIN batches ON batch_log.batch_id=batches.id
JOIN ramses.tasks ON ramses.batch_log.batch_id=ramses.tasks.batch_id
JOIN protocase.tblusers on ramses.batch_log.userid = protocase.tblusers.userid
WHERE DATE(ramses.batch_log.start_time) > "2011-02-01"
AND ramses.batch_log.time_elapsed > "00:03:00"
AND DATE(ramses.batch_log.start_time) < now()
AND protocase.tblusers.active = 1
AND protocase.tblusers.userid NOT in ("ksnow","smanning", "dstapleton")
GROUP BY userid, batches.operation_id, date(start_time)
ORDER BY start_time, userid ASC
Since this is to be compared with the time from the current payperiod it causes an error.
Our pay periods start on a Sunday, the first pay period was 2011-02-01 and our last pay period started the 4th of this month. How do I put that into my where statement to strip the most recent pay period out of the query?
EDIT: So now I'm using date_sub(now(), INTERVAL 2 WEEK) but I really need a particular day of the week(SUNDAY) since it is wednesday it's chopping it off at wednesday.
You want to use DATE_SUB, and as an example.
Specifically:
select DATE_SUB(curdate(), INTERVAL 2 WEEK)
gets you two weeks ago. Insert the DATE_SUB ... part into your sql and you're good to go.
Edit per your comment:
Check out DAYOFWEEK:
and you can do something along the lines of:
DATE_SUB(DATE_SUB(curdate(), INTERVAL 2 WEEK), INTERVAL 2 + DAYOFWEEK(curdate()) DAY)
(I don't have a MySql instance to test it on .. but essentially subtract the number of days after Monday.)
Question isn't quite clear, especially after the edit - it isn't clear now is the "pay period" two weeks long or do you want just last two weeks back from last sunday? I assume that the period is two weeks... then you first need to know how many days the latest period (which you want to ignore, as it isn't over yet) has been going on. To get that number of days you can use expression like
DATEDIFF(today, FirstPeriod) % 14
where FirstPeriod is 2011-02-01. And now you strip that number of days from the current date in the query using date_sub(). The exact expression depends on how the period is defined but you should get the idea...