Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting distinct dates from datetime column in a table

Tags:

sql

mysql

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.

like image 512
rvk Avatar asked Mar 17 '11 06:03

rvk


People also ask

How do we select distinct data from table?

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.

How can I get distinct values for a particular column in SQL?

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.

How do you select unique values in a column?

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.


1 Answers

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
like image 80
Hassan Avatar answered Sep 22 '22 04:09

Hassan