Selecting distinct dates from datetime column in a table
I have a table
id | message | date_posted
1 | testing | 2011-03-08 03:15:13
2 | testing | 2011-03-06 03:15:13
3 | testing | 2011-03-08 03:15:13
And need a query w开发者_StackOverflowhere I return a list of distinct dates in desc order. I tried to formulate a query like so
SELECT DISTINCT CAST(`date_posted` AS DATE) AS dateonly FROM table
This gives me dates but they're not distinct and have duplicates.
Any ideas? (Using php/mysql)
MAJOR EDIT:
Forgot an important piece of information. I'm trying to get unique dates based on month and year.
2011-03-08 03:15:13
2011-03-06 03:15:13
2011-03-02 03:15:13
2011-03-01 03:15:13
2011-02-01 03:15:13
So running the query would only return [2011-03-dd,2011-02-01] (dd being any day)
Apologize for not stating this.
Your query will return unique DATES, as you've specified. If you want to get just unique MONTHS/YEARS, you should either modify you dates in a way, that each date becomes the first day of the month, or you should just go with some string representation like 'YYYY-MM'. Sorry, I can't write you an exact code how to do this, as I do not develop on mysql, but I think this should get you somewhere :)
SELECT DISTINCT YEAR(date_posted), MONTH(date_posted) FROM table
Working example
create table dts (dt datetime);
insert dts select '2011-03-08 03:15:13';
insert dts select '2011-03-07 03:15:13';
insert dts select '2011-03-09 03:15:13';
insert dts select '2011-03-08 03:15:13';
select distinct cast(dt as date) from dts;
Output
"cast(dt as date)"
"2011-03-08"
"2011-03-07"
"2011-03-09"
Query for distinct Year-Month
select date(date_format(dt, '%Y-%m-1')) as dt
from dts
group by dt;
Output (the result is a date column, with the day set to '1')
2011-03-01
SELECT DATE(`date_posted`) AS dateonly
FROM table
GROUP BY DATE(`date_posted`)
SELECT DISTINCT date(date_format(COLUMN_NAME, '%Y-%m-%d')) as uniquedates from TABLE_NAME
精彩评论