How to dynamically pull MYSQL date queries? - mysql

I am trying to select data from two periods (Last 30 days and Previous 30 days)
So two 30 day periods.
I have the last 30 day period down:
SELECT ProductID, ProductIDintarget,date_format(Date,'%m/%d/%Y'),SUM(Rev)
FROM datatable
WHERE Date BETWEEN CURDATE()-1 - INTERVAL 31 DAY AND CURDATE()
GROUP BY ProductIDintarget
That is working fine, but now I'm struggling to get the previous 30 day period.
I have tried changing the WHERE statement as:
WHERE Date BETWEEN CURDATE()-32 - INTERVAL 31 DAY AND CURDATE()-32
but no luck..

You can use DATE_ADD() or DATE_SUB() like this:
SELECT
ProductID,
ProductIDintarget,
DATE_FORMAT(Date,'%m/%d/%Y'),
SUM(Rev)
FROM datatable
WHERE `Date` < (DATE_ADD(CURDATE(), INTERVAL 1 MONTH))
AND `Date` > (DATE_SUB(CURDATE(), INTERVAL 2 MONTH))
GROUP BY
ProductID,
ProductIDintarget,
`Date`
Note:- You should backticks if you have keywords as column names.

Related

mysql query how to show each day's total cash sale for the current week

I have the following mysql query which shows the each day's total cash sale for the current week.
SELECT
sum(Price) as totalprice,
WEEKDAY(CreatedOn) as dayno,
DATE(CreatedOn) as CreatedOn,
AgentID
FROM records
WHERE CreatedOn BETWEEN (CURDATE()-WEEKDAY(CURDATE())) AND CURDATE()
GROUP BY DATE(CreatedOn)
When I run the query it looks like this:
There are records on 30th November(today's date). So,
day 0 (Monday) no cash sale
day 1 (Tuesday) $5049
day 2 (Wednsday) $99
Nothing is displayed for day 3 (Thursday/today). I cannot figure out the reason there are definitely record in the database but cannot get them to be displayed. I would appreciate any help.
CURDATE() is today's date but at 00:00:00+0000000
"push up" the higher date by 1 day and avoid using between for date/time ranges:
WHERE CreatedOn >= date_sub(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY)
AND CreatedOn < date_add(CURDATE(), INTERVAL 1 DAY)
select date_sub(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY)
, date_add(CURDATE(), INTERVAL 1 DAY)
The condition in the query currently specifies on or before midnight today, so any rows for today after midnight are going to be excluded.
I think you are intending to specify CreatedOn before midnight of the following day.
I also suggest you don't subtract an integer value from a date/datetime, and instead use the INTERVAL syntax
WHERE CreatedOn >= CURDATE() - INTERVAL WEEKDAY(CURDATE()) DAY
AND CreatedOn < CURDATE() + INTERVAL 1 DAY
To test those expressions before we include them in a query, we can run a SELECT statement:
SELECT CURDATE() - INTERVAL WEEKDAY(CURDATE()) DAY
, CURDATE() + INTERVAL 1 DAY
and verify that those expressions are returning what we expect, the values we want to use. For testing, we can replace CURDATE() with a date value to test the return for days other than today.

SELECT date BETWEEN dates with interval

I have a date column in my database. I use SELECT COUNT to calculate the rows between today and 15 days ago:
SELECT count(date) as date
FROM `inv`
WHERE user_id='2'
AND date BETWEEN CURDATE() - INTERVAL 15 DAY
AND CURDATE()
This SQL statement is working. But now I want use SELECT COUNT to calculate the rows between today(-15 days) and 30 days ago. But I am getting an error when I try the following statement:
SELECT count(date) as date
FROM `inv`
WHERE user_id='2'
AND date BETWEEN date(CURDATE(),INTERVAL -15 day)
AND date(CURDATE(),INTERVAL -30 day)
Also I want to know how I can SELECT the rows where the date is more than 30 days ago. Can someone help me with this?
You can use the below to get rows between 15 to 30 days old.
SELECT count(date) as date
FROM `inv`
WHERE user_id=2
AND date BETWEEN CURDATE() - INTERVAL 30 DAY
AND CURDATE() - INTERVAL 15 DAY
Similarly you can use below to get rows that are older than 30 days.
SELECT count(date) as date
FROM `inv`
WHERE user_id=2
AND date < CURDATE() - INTERVAL 30 DAY
Try This
SELECT * FROM "table name" WHERE "user_id=2"
BETWEEN CURDATE() - INTERVAL 30 DAY
AND CURDATE() - INTERVAL 15 DAY

Apply group by and limit offset together in MySQL

I have a table name transactions where data rows are stored with a date
Like
`trans_id` `amount` `tdate`
I want to filter that data like last 30 days, last 31st 60 days, last 61-90 days calculate the overall amount also
My queries are
For last 30 days
SELECT SUM(amount) AS amt FROM transactions GROUP BY DATE(tdate) ORDER BY DATE(tdate) DESC LIMIT 30
Working fine and show SUM of amount (last 30days)
But for last 31-60 days not working
SELECT SUM(amount) AS amt FROM transactions GROUP BY DATE(tdate) ORDER BY DATE(tdate) DESC LIMIT 60,31
How to solve it ? I do want to include only 31 to 60 days amount only
Use the following: (It returns data between today and last 30 days)
SELECT DATE_FORMAT(DateCol, '%m/%d/%Y')
FROM Table
WHERE DateCol BETWEEN CURDATE() - INTERVAL
30 DAY AND CURDATE()
Or more precisely, this will do the trick:
DateCol BETWEEN (NOW() - INTERVAL 60 DAY)
AND (NOW() - INTERVAL 30 DAY)
CURDATE() works for only date portion. If you have DateTime column, then NOW() will do.

add days to a date column and then check if it's between two dates SQL

I need a sql query to find the data from a employee table.
Startdate is present in employee table.
I need to add 90 days in startdate and then I need to check if the startdate lies in the current month or not.
I did try below query:
SELECT *
FROM `employees`
WHERE DATE_ADD(str_to_date(startdate, '%m/%d/%Y'),INTERVAL 90 DAY) BETWEEN '09/01/2016' AND '09/30/2016'
but its not giving me the expected results.(I do have data which should show up if the query is correct.)
Hi i did change the query and ran, please see the result. I am getting results of next month too :(
This is the query
SELECT id,startdate from employees WHERE str_to_date(startdate, '%m/%d/%Y') between DATE_SUB(DATE_FORMAT(NOW(), '%Y-%m-01'), INTERVAL 90 day) -- start of this month - 90 days and DATE_SUB(LAST_DAY(NOW()), INTERVAL 90 day)
Query output
Rephrased my query...
Where the event was within the dates 90 days before the start and end of this month
WHERE str_to_date(startdate, '%m/%d/%Y') between
DATE_SUB(DATE_FORMAT(NOW(), '%Y-%m-01'), INTERVAL 90 day) -- start of this month - 90 days
and DATE_SUB(LAST_DAY(NOW()), INTERVAL 90 day) -- End of this month - 90 days
or, for three months
WHERE str_to_date(startdate, '%m/%d/%Y') between
DATE_SUB(DATE_FORMAT(NOW(), '%Y-%m-01'), INTERVAL 3 month) -- start of this month - 3 months
and DATE_SUB(LAST_DAY(NOW()), INTERVAL 3 month) -- End of this month - 3 months

How to get average sales of an employee before certain sale in MySQL?

Suppose I have a table with 3 columns: EMPLOYEE_ID, NUM_SALES, DATE. Simply this is the table of Employees indicating daily sales. For each row in the table, I try to compute this; average number of sales of that EMPLOYEE_ID in the last K days excluding this day.
How can I query this in MySQL? I try to group by with EMPLOYEE_ID and DATE but I cannot figure out how to find last K sales for each row.
To select an interval of days, you can use MySQL's DATE_SUB() function:
WHERE `date` >= DATE_SUB(NOW(), INTERVAL 3 DAY)
This will select all records that are from the past 3 days. However, to exclude "today" from that:
WHERE `date` BETWEEN
DATE_SUB(NOW(), INTERVAL 3 DAY)
AND DATE_SUB(NOW(), INTERVAL 1 DAY)
After that you should be able to GROUP BY the employee_id to get what you're after:
SELECT
employee_id, avg(num_sales) AS avg_num_sales
FROM
employee_table
WHERE `date` BETWEEN
DATE_SUB(NOW(), INTERVAL 3 DAY)
AND DATE_SUB(NOW(), INTERVAL 1 DAY)
GROUP BY
employee_id
You need to be able to select items from your table, let's call it dailysale, by date.
Here's what you do.
SELECT employee_id, AVG(num_sales) AS avg_sales
FROM dailysale
WHERE date >= CURDATE() - INTERVAL 3 DAY
AND date < CURDATE()
GROUP BY employee_id
This uses two WHERE clauses to winnow down the date range you're using. date >= CURDATE() - INTERVAL 3 DAY excludes all records before midnight three days ago, and date < CURDATE() excludes all records on or after midnight today.
You need to use CURDATE() rather than NOW() because, well, NOW() includes the date and the present time of day. date < NOW() will include today's sales, because your date column only records dates and not times.
If you want to list the employees in order of sales, you could add
ORDER BY AVG(num_sales) DESC, employee_id
to the query.