This question already has answers here:
Query to get all rows from previous month
(13 answers)
Closed 7 years ago.
I am trying to call last month data from mysql but it gives me the data from previous years as well, for example august 2011, august 2012 .... august 2015. I used different functions to get the interval of last month but no success. this means the Sum of order from database is also incorrect.
Query 1:
SELECT sku,
order_date,
sum(`order_total`) AS sales
FROM `tableOrder`
WHERE `order_status`='Shipped'
AND MONTH(STR_TO_DATE(order_date, '%m/%d/%Y')) = MONTH(CURDATE() - INTERVAL 1 MONTH)
GROUP BY STR_TO_DATE(order_date, '%m/%d/%Y')
ORDER BY sales DESC
Query 2:
SELECT sku,
order_date,
sum(`order_total`) AS sales
FROM `tableOrder`
WHERE `order_status`='Shipped'
AND MONTH(STR_TO_DATE(order_date, '%m/%d/%Y')) = MONTH(DATE_ADD(Now(), INTERVAL -1 MONTH))
GROUP BY STR_TO_DATE(order_date, '%m/%d/%Y')
ORDER BY sales DESC
Add an extra condition for the year:
SELECT sku,order_date,sum(`order_total`) as sales FROM `tableOrder`
WHERE `order_status`='Shipped'
AND MONTH(STR_TO_DATE( order_date, '%m/%d/%Y' )) = MONTH(CURDATE() - INTERVAL 1 MONTH)
AND YEAR(order_date) = YEAR(NOW())
GROUP BY STR_TO_DATE( order_date, '%m/%d/%Y' )
ORDER BY sales desc
Related
I have this query:
SELECT DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%Y') AS `year`
, DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%b') AS `month`
, COUNT(odd_Id) as total, status, odd_date_created FROM odd_data
WHERE status = 1
GROUP BY DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%m')
HAVING DATE_FORMAT(odd_date_created + INTERVAL -3 DAY,'%Y') = 2018
$yearToDate will dynamically from select dropdown. When user select 2017, managed to get the data but if you select 2018 there is no data retrun.
Can somebody help me.
The problem is with your GROUP BY clause. Since you are grouping by month and the first data for each month is in 2017, the value of DATE_FORMAT(odd_date_created + INTERVAL -3 DAY,'%Y') in the select will almost certainly (although it's not guaranteed as there is no order implied) be 2017. You need to GROUP BY the year as well so that you get data for each month in each year. Then you can select specific years using HAVING. Note that you can use aliases in GROUP BY and HAVING clauses, so you can rewrite your query as:
SELECT DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%Y') AS `year`,
DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%b') AS `month`,
COUNT(odd_Id) as total, status, odd_date_created FROM odd_data
WHERE status = 1
GROUP BY year, month
HAVING year = 2018
Note that having status and odd_date_created in this query is pointless as they will return random values from the set of entries which match the WHERE and HAVING clauses.
I have a table called payment it has date field, i have a customer called Mark who has been making payment every day for 3 years
Table: Payment
Fields: Name , Amountpaid, date
I want to display payment record made by mark every 3 month and also the total Amountpaid for 3 years
How i want the result to look like
First 3 months payment record table
total Amountpaid at the bottom of the table
second 3 months payment record table
total Amountpaid at the bottom of the table
Third 3 months payment record table
total Amountpaid at the bottom of the table
and so on for 3 years
Please do help out
It seems like you're looking for a SQL solution for this, but databases are for holding data, they aren't for formatting it into a report. To this end my advice would be: Don't try and do this in the database, do it in the front end code instead
It will be very simple to run a query like
SELECT * FROM payment WHERE
name = 'mark' and
`date` between date_sub(now(), interval 3 year) and now()
ORDER BY date
And then put the results into an HTML table usig a loop, and a variable that keeps track of the amount paid total. Every 3 months reset the variable. If you want MySQL to do a bit more data processing to help out you can do this:
SELECT * FROM
payment
INNER JOIN
(SELECT YEAR(`date`) + (QUARTER(`date`)/10) as qd, SUM(amountpaid) as qp FROM payment WHERE name = 'mark' GROUP BY YEAR(`date`), QUARTER(`date`)) qpt
ON
qpt.qd = YEAR(`date`) + (QUARTER(`date`)/10)
WHERE
name = 'mark' AND
`date` between date_sub(now(), interval 3 year) and now()
ORDER BY `date`
This will give all mark's data row by row and an extra two columns (that mostly repeat themselves over and over) showing the year and quarter (3 months) of the year like 2017.1, 2017.2, together with a sum of all payments made in that quarter. Formatting it in the front end now won't need a variable to keep a running total of the amount paid
This is about the limit of what you should do with formatting the data in the database (personal opinion). If, however, you're determined to have MySQL do pretty much all this, read on..
Ysth mentioned rollup, which is intended for summarising data.. such a solution would look like this:
SELECT
Name, `date`, SUM(amountpaid) as amountpaid
FROM
payment
WHERE
name = 'mark' AND
`date` between date_sub(now(), interval 3 year) and now()
GROUP BY
name,
YEAR(`date`) + (QUARTER(`date`)/10),
`date`
WITH ROLLUP
The only downside with this approach is you also get a totals row for all payments by mark. To suppress that, use grouping sets instead:
SELECT
Name, `date`, SUM(amountpaid) as amountpaid
FROM
payment
WHERE
name = 'mark' AND
`date` between date_sub(now(), interval 3 year) and now()
GROUP BY GROUPING SETS
(
(
name,
YEAR(`date`) + (QUARTER(`date`)/10),
`date`
),
(
name,
YEAR(`date`) + (QUARTER(`date`)/10)
)
)
You can use a group by on the year and month divided by 3 and truncated using floor
SELECT
EXTRACT(YEAR_MONTH FROM `date`),
SUM(`Amountpaid`)
FROM
`Payment`
WHERE
`Name` = 'Mark'
AND `date` >= DATE_SUB(NOW(), INTERVAL 3 YEAR)
GROUP BY
EXTRACT(YEAR FROM `date`),
FLOOR(EXTRACT(MONTH FROM `date`) / 3)
For the total you will need to iterate the result set and sum up the amounts paid, or if you want it as the final record you could do a UNION SELECT but this would be ineffecient, but for completeness it is below:
SELECT
EXTRACT(YEAR_MONTH FROM `date`),
SUM(`Amountpaid`)
FROM
`Payment`
WHERE
`Name` = 'Mark'
AND `date` >= DATE_SUB(NOW(), INTERVAL 3 YEAR)
GROUP BY
EXTRACT(YEAR FROM `date`),
FLOOR(EXTRACT(MONTH FROM `date`) / 3)
UNION SELECT
NULL,
SUM(`Amountpaid`)
FROM
`Payment`
WHERE
`Name` = 'Mark'
AND `date` >= DATE_SUB(NOW(), INTERVAL 3 YEAR)
This is for get summary per 3 months :
select year(date)*100+floor(month(date)/3) as period, sum(amountpaid)
from payment
where name = 'mark' and (date between '2014-01-01' and '2017-01-01')
group by year(date)*100+floor(month(date)/3)
order by period
And this is how to get summary 3 year :
select sum(amountpaid) from payment where name = 'mark' and (date between '2014-01-01' and '2017-01-01')
You can change the date between for your need
I am trying to call data from SQL table that is only 3 days old
My table has a lbs-date column in it and is date format. I have tried the following but get no result from the query at all
$result = mysql_query("SELECT *, DATE_FORMAT(datetime, '%y,%m,%d') FROM lbs_trace_etrack
WHERE lbs_date(datetime) = CURDATE() - INTERVAL 3 DAY
ORDER BY lbs_date DESC")
Is there any other way I can call only the last 3 days of information from the SQL my date format is Y/M/D
SELECT *, DATE_FORMAT(lbs_date, '%y,%m,%d')
FROM lbs_trace_etrack
WHERE lbs_date >= CURDATE() - INTERVAL 3 DAY
ORDER BY lbs_date DESC
check DATE_FORMAT. Its syntax is DATE_FORMAT(<date>,format) . Use like this :
SELECT *, DATE_FORMAT(lbs_date , '%y,%m,%d') FROM lbs_trace_etrack
WHERE lbs_date = CURDATE() - INTERVAL 3 DAY
ORDER BY lbs_date DESC
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
MySQL Query GROUP BY day / month / year
I have the following mysql:
SELECT MONTH( FROM_UNIXTIME( `timeStamp` ) ) as month , COUNT( `id` ) as count
FROM `discusComments`
GROUP BY MONTH( FROM_UNIXTIME( `timeStamp` ) )
ORDER BY MONTH( FROM_UNIXTIME( `timeStamp` ) ) ASC
LIMIT 15
It gets the amount of entries made per month in the past 15 months. I was wondering WHY it only displayed the past 12 months ... then I realised the count was an aggregate of all years and not unique per month year. So the value for december could be 2012 and 2011 together.
I donÄt want this. I want to get the past 15 months and the amount of entries made for UNIQUE month year, e.g. december 2012, november 2012 etc.
The most straight forward idea I have on this is normally to change the format of the date value to a unique and speaking string, like 2012-12 for December 2012 and 2011-10 for October 2011 etc.
A function you can use for that is DATE_FORMAT():
DATE_FORMAT(FROM_UNIXTIME(timeStamp), '%Y-%m')
These strings are then easily sortable, e.g. ASC:
2011-10
2011-11
2011-12
...
2012-10
2012-11
2012-12
Example SQL query:
SELECT
DATE_FORMAT(FROM_UNIXTIME(timeStamp), '%Y-%m') as month,
COUNT(id) as count
FROM discusComments
GROUP BY month
ORDER BY month ASC
LIMIT 15
Add year to your SELECT column list and add the alias to GROUP BY too.
SELECT YEAR(FROM_UNIXTIME(`timestamp`)) AS year,
MONTH(FROM_UNIXTIME(`timestamp`)) AS month,
COUNT(`id`) AS count
FROM `discuscomments`
GROUP BY year,
month
ORDER BY year,
month
LIMIT 15
Try this
months_between(to_date ('2009/05/15', 'yyyy/mm/dd'),
to_date ('2009/04/16', 'yyyy/mm/dd'))
I've a table with a datetime (format: 'Y-m-d H:i:s') 'created' field and 'amount' (integer) field in each row. Now I want to find out month wise total 'amount' in last year. How can I do this?
EDIT
I made an edit to clarify the actual problem. so basically I want to know total 'amount' in each month, but only for the last year.
EDIT2
Last year means last 365 days. So somewhere I've to consider 'current day'?
EDIT3
My bad, actually last year is last 12 months. So number of days would be between 336 and 365.
Try this (updated to answer your "edit3"):
SELECT
YEAR(created) as year,
MONTH(created) AS month,
SUM(amount) AS total_amount
FROM table1
WHERE created
BETWEEN DATE(NOW()) - INTERVAL (DAY(NOW()) - 1) DAY - INTERVAL 11 MONTH
AND NOW()
GROUP BY YEAR(created), MONTH(created)
ORDER BY YEAR(created), MONTH(created);
Example result (when run in April 2010):
year month total_amount
2009 5 26
2010 1 20
Note also that months with no entries will not be returned at all (rather than being returned with total_amount = 0).
Test data:
CREATE TABLE table1 (created datetime NOT NULL, amount INT NOT NULL);
INSERT INTO table1 (created, amount) VALUES
('2010-01-01 13:56:23', 5),
('2010-01-04 13:56:23', 15),
('2009-05-04 13:56:23', 26);
This returns the count and total amount for last year:
SELECT MONTH(created) as month_updated,
COUNT(created) as month_updates, SUM(amount) as month_total FROM table
WHERE created BETWEEN DATE_ADD(NOW(), INTERVAL -1 YEAR) AND NOW()
GROUP BY MONTH(created)
Or, if you specifically mean just 2009:
SELECT MONTH(created) as month_updated,
COUNT(created) as month_updates, SUM(amount) as month_total FROM table
WHERE created BETWEEN '2009-01-01 00:00:00' AND '2009-12-31 23:59:59'
GROUP BY MONTH(created)
SELECT count(some_row) AS or_whatever FROM your_table GROUP BY MONTH(update);
To be more specific (with your update):
SELECT SUM(amount) FROM table_name GROUP BY MONTH(created);