sql order by most recent dates - php

I have this table in my database:
INSERT INTO `shop_stats` (`date`, `value`) VALUES
('09/2014', 326),
('08/2014', 1007),
('07/2014', 1108),
('06/2014', 1027),
('05/2014', 895),
('04/2014', 650),
('03/2014', 683),
('02/2014', 563),
('01/2014', 499),
('12/2013', 568),
('11/2013', 522),
('10/2013', 371),
('09/2013', 347),
('08/2013', 376),
('07/2013', 418),
('06/2013', 567),
('05/2013', 357);
i need to find a way to display the last 12 months.
I tried this:
SELECT * FROM shop_stats ORDER BY date DESC LIMIT 12
But it doesn't work correctly.
Any suggestions ?

SELECT * FROM shop_stats WHERE date >= DATE_SUB(NOW(),INTERVAL 1 YEAR) LIMIT 12

Your "dates" are stored as strings, presumably with the month first. So, the following order by should work
order by right(date, 4), left(date, 2)
You need to put the year before the month for ordering purposes.
If you want the last twelve months, I would recommend:
where right(date, 4) * 12 + left(date, 2) >= year(now()) * 12 + month(now())
order by right(date, 4), left(date, 2)
The where statement converts the dates to a number of months, for both the "date" column in your data and for the current time.

You can simply use STR_TO_DATE like this
SELECT
*
FROM
shop_stats
order by
STR_TO_DATE(date, '%m/%Y') DESC LIMIT 12
Demo

I suppose your field date has a type string
So you try this:
SELECT * FROM shop_stats
ORDER BY SUBSTRING(date, 4, 4) desc,
substring(date, 1, 2) DESC LIMIT 12
Show Sql Fiddle

You can take a look at DATE_SUB
SELECT * FROM shop_stats where date >= DATE_SUB(now(), INTERVAL 12 MONTH) ORDER BY date
Edit:
How about converting the string to date & doing the appropriate date operations in the sql ?
SELECT DATE
,t1.value
FROM (
SELECT DATE
,STR_TO_DATE(CONCAT (
'01/'
,DATE
), '%d/%m/%Y') date_
,value
FROM shop_stats
) t1
WHERE t1.date_ >= DATE_SUB(now(), INTERVAL 12 MONTH)
ORDER BY t1.date_ DESC
http://sqlfiddle.com/#!2/2be05/8

select * from shop_stats where date >= (NOW() - INTERVAL 12 MONTH) ORDER BY date

Related

PHP: Combine these two SQL queries into one

I use MariaDB and have a table where each row has a date and a score.
I want to first show the rows where the date is 3 days old or newer, sorted by the score - then show the rest (more than 3 days old) sorted by date.
Since my date is stored in unix time, it's fairly easy to have php calculate 3 days from before now and use that as my $scoreTimeLimit variable in the below:
Here are my two queries:
SELECT * FROM myTable WHERE myDate > $scoreTimeLimit ORDER BY myPopularityScore DESC
SELECT * FROM myTable WHERE myDate < $scoreTimeLimit ORDER BY myDate DESC
However, I would VERY much like to have only 1 query instead of two. Can it be done...?
This is a job for UNION.
SELECT * FROM (
SELECT 0 ord1, NOW() as ord2, *
FROM myTable WHERE myDate > NOW() - INTERVAL 3 DAY
UNION ALL
SELECT 1 ord1, myDate as ord2, *
FROM myTable WHERE myDate <= NOW() - INTERVAL 3 DAY
) a
ORDER BY ord1, ord2 DESC, myPopularityScore
The inner query gives you a single result set with a couple of extra columns added on to help you manage your sorting.

Specify PHP code to select dates and records 3 days old

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

What should be MySQL query for the following?

I wish to show upcoming birthday records on dashboard. I have MySQL table 'contacts' which
has field dob (DATE YYYY-MM-DD). I want to retrieve all the records with birthday is coming
in next 15 days. e.g is: birthday is 1986-03-24 it should be in result.
Take a look at MySQL DATE_ADD and INTERVAL.
By using both as below you can get record that are coming in next 15 days.
SELECT * FROM user WHERE dob BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 15 DAY)
FOR birthrate comparison.
MAKEDATE(YEAR(NOW() + INTERVAL 15 DAY), DAYOFYEAR(birthday)) BETWEEN CURDATE() AND CURDATE() + INTERVAL 15 DAY
SQLFiddle Demo
You have to use the date in mysql query as:
SELECT FROM table_name WHERE timestamp_row BETWEEN
'2011-01-01 00:00:00' AND '2011-01-02 23:59:59';
You are doing the B'Day dates of users and thus hope this would be do the trick of formatting and selection of date
select id from my_table
where
timestamp < date_format(date_add(CURRENT_TIMESTAMP(), interval 1 day),
'%Y%m%d000000' ) AND timestamp >= date_format(CURRENT_TIMESTAMP(),
'%Y%m%d000000')
Can do by this way also
SELECT * FROM person WHERE IF ( MONTH( NOW() ) < 12,
MONTH( birthdate ) = MONTH( NOW() ) + 1, MONTH( birthdate ) = 1)
You can use this query. Try Out
SELECT * FROM TableName
WHERE REPLACE(BirthDate, DATEPART(YEAR, BirthDate), DATEPART(YEAR, GETDATE())) BETWEEN GETDATE() AND DATEADD(DAY, 15, GETDATE())

what where clause should I use to get objects greater than the creation date?

In my DB the objects are saved with creation date in the format, dd-month-year hours:seconds (example 2011-12-07 09:59:41). What sql commands should I use to get objects created after April 2012?
-- After April 1st, including
SELECT *
FROM mytable
WHERE creationDate >= CAST('2012-04-01' AS DATE)
-- After April 1st, excluding
SELECT *
FROM mytable
WHERE creationDate >= '2012-04-01' + INTERVAL 1 DAY
-- After April
SELECT *
FROM mytable
WHERE creationDate >= '2012-04-01' + INTERVAL 1 MONTH
SELECT * FROM mytable WHERE CreationDate > '2012-04-00'
WHERE DATE_FORMAT(creationDate, '%d/%m/%Y') >= STR_TO_DATE('01/05/2012', '%d/%m/%Y')
(you are asking after april 2012, which is may)
Try this link
You want the bit at the bottom.
Example:
SELECT * from table where DATE >='2008-12-03';

HOw to SELECT * (all) which date start from the last day of last month to the first day of next month

use PHP and MySQL and want to use SELECT statement which date_post(datetime variable) start at the last date of last month and to date the first day of next month, help me please.
Thank you in advance.
my database: 'id', 'content', 'image', 'date_post',
etc. and I try to use
$today = getdate();
$thisyear=$today['year'];
$thismon=$today['mon'];
$date_start=$thisyear.'-'.$thismon.'-01';
$date_end=$thisyear.'-'.($thismon+1).'-01';
$sql="SELECT *, DATE_FORMAT(date_post, '%d-%m-%Y') AS datepost
FROM my_table
WHERE date_post BETWEEN date('$date_start')
AND date('$date_end')
ORDER BY date_post DESC";
It makes with one query in MySQL, without any PHP:
SELECT * FROM `table_name`
WHERE DATE(`date_post`) >= DATE_FORMAT(CURDATE() - INTERVAL 1 MONTH, CONCAT('%Y-%m-', DAY(LAST_DAY(CURDATE() - INTERVAL 1 MONTH))))
AND DATE(`date_post`) <= DATE_FORMAT(CURDATE() + INTERVAL 1 MONTH, '%Y-%m-01');
Ensuring that the query will not scan the full table but will use the index of date_post (if there is one!):
SELECT *
FROM myTable
WHERE date_post < LAST_DAY(CURDATE())
+ INTERVAL 2 DAY
AND date_Post >= LAST_DAY( LAST_DAY( CURDATE()) - INTERVAL 1 MONTH )
If it is run today ( 2011-07-01 ), it will give all datetimes between 2011-06-31 00:00:00 and 2011-08-01 23:59:59.

Categories