Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL How to remove duplicates within select query?

Tags:

sql

I have a table which looks like that:

alt text

As You see, there are some date duplicates, so how to select only one row for each date in that table?

the column 'id_from_other_table' is from INNER JOIN with the table above

like image 721
Tony Avatar asked Sep 12 '10 15:09

Tony


People also ask

How do I select without duplicates in SQL?

If you want the query to return only unique rows, use the keyword DISTINCT after SELECT . DISTINCT can be used to fetch unique rows from one or more columns.

How can I delete duplicate records in SQL using distinct?

Introduction to SQL DISTINCT operator Note that the DISTINCT only removes the duplicate rows from the result set. It doesn't delete duplicate rows in the table. If you want to select two columns and remove duplicates in one column, you should use the GROUP BY clause instead.


2 Answers

There are multiple rows with the same date, but the time is different. Therefore, DISTINCT start_date will not work. What you need is: cast the start_date to a DATE (so the TIME part is gone), and then do a DISTINCT:

SELECT DISTINCT CAST(start_date AS DATE) FROM table;

Depending on what database you use, the type name for DATE is different.

like image 113
Thomas Mueller Avatar answered Nov 08 '22 22:11

Thomas Mueller


Do you need any other information except the date? If not:

SELECT DISTINCT start_date FROM table;
like image 39
amorfis Avatar answered Nov 08 '22 20:11

amorfis