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 where 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.
The SQL SELECT DISTINCT Statement The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.
To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns. The column names has to be separated with comma.
In Excel, there are several ways to filter for unique values—or remove duplicate values: To filter for unique values, click Data > Sort & Filter > Advanced. To remove duplicate values, click Data > Data Tools > Remove Duplicates.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With