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'))
Related
I want to list the scores, by month, for something that happened over the last 12 months. I noticed my query below was combining the results of the first partial month with the results of the last partial month. That is, my July report combined July 9-31, 2015 with July 1-8 2016 (now is July 8). I only want the latest month to represent the latest year. Here is what I was using...
$query = "SELECT record_id,
time_scored,
MONTH(time_scored) as month_added,
score, comment
FROM records
WHERE score IS NOT NULL AND
time_scored >= DATE_SUB(curdate(),INTERVAL 12 MONTH)
ORDER BY time_scored DESC";
Any help would be appreciated. Thanks!
Subtract 12 months from next months 1st day
$query = "SELECT record_id,
time_scored,
MONTH(time_scored) as month_added,
score, comment
FROM records
WHERE score IS NOT NULL AND
time_scored >= DATE_SUB(DATE_ADD(subdate(curdate(), (day(curdate())-1)), INTERVAL 1 MONTH),INTERVAL 12 MONTH)
ORDER BY time_scored DESC";
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
Say I've got a simple mysql table with columns id, title, date. Each day can have several rows, but not every day has a row. For example there might be 5 rows with June 15th as the date, but zero rows with June 14th as the date. How can I get all results from the past 7 days, excluding June 14th because it has no rows. So I'm not just subtracting 7 days from the current date. I want to get only the past 7 days which have any rows at all.
Then I want to return each day as a single result, like a group by date, but by the year/month/day part of the timestamp, so that what I get back is only 7 results, and each result is like an array of individual rows.
I hope that makes sense. Any ideas?
Edit:
I realized I can do it something like this:
WHERE Date BETWEEN DATE_SUB( NOW(), INTERVAL DATEDIFF( NOW(), (SELECT Date FROM test GROUP BY Date LIMIT 7,1 ) ) DAY ) and NOW()
But this gives an SQL syntax error. What I'm trying to do is a subquery and group by date to get one result for each day, and return one result starting at offset 7, then do a DATEDIFF on that to get the number of days that DATE_SUB should put in the INTERVAL x DAYS
You won't be able to get the same day results back as an array, but you can group it by date, with the titles comma separated:
SELECT GROUP_CONCAT(title) AS titles, date
FROM test
WHERE date > DATE_SUB(CURDATE(), INTERVAL 7 DAY)
GROUP BY date;
Then in PHP, do something like this:
foreach ($results as $row)
{
echo $row['date'];
foreach ($row['titles'] as $title)
{
echo $title;
}
}
Figured it out: It works!
WHERE Date BETWEEN DATE_SUB(NOW(), INTERVAL (DATEDIFF( NOW(), (SELECT Date FROM test GROUP BY Date ORDER BY Date DESC LIMIT 8,1 ) ) ) DAY) and NOW()
I was missing a parentheses, and I had to add ORDER BY and DESC to the subquery.
I search and get 10 records as result.I have two drop down boxes.one will have month as value and other one will have year as the value.Say those 10 records have same year and 5 have month as jan and other five has month as feb.
When user clicks feb then five ids will be passed to my query but i need to pull the younger document.2 docs were inserted on 5th of feb and other tow 10 feb and remaining one 25feb.i need to pull this 25th feb document.
how to select this using select statement?
You can extract day and time from the database and have them shown to the user so he can select the correct document, otherwise you can solve with:
SELECT *
FROM TABLE
WHERE month = 'Feb'
AND year = 2011
AND day = (select max(day) from table where month = 'Feb' and year = 2011 )
But I'm supposing a lot of information here, these infos should help me help you out:
name of table
fields and field types
Do you have a way to keep correct track of timestamps and dates?
Presumably you have some date_inserted column in your database - if so, you can add
ORDER BY date_inserted DESC LIMIT 1
This will put them in reverse date order, and LIMIT 1 will cause it to only return 1 result
This should work:
SELECT *
FROM `table`
WHERE MONTH(`insert_date`) = 2
AND YEAR(`insert_date`) = 2011
ORDER BY `insert_date` DESC
LIMIT 1;
Note: the above assumes you have a field in your table for storing the date on which the document was created/inserted. Please replace insert_date and table in the above query with the respective column name and table name.
EDITED after this comment "date stores date,month stores month and year stores year"
SELECT *
FROM `table`
WHERE `month` = 2
AND `year` = 2011
ORDER BY `year` DESC, `month` DESC, `date` DESC
LIMIT 1;
I've assumed that in the month column you are storing numbers, 1 for Jan, 2 for Feb and so on. If however you are storing the 3-letter month name, then instead of "`month` = 2" please use this:
MONTH(STR_TO_DATE(`month`, '%b')) = 2
Hope this should work.
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);