Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DISTINCT and TOP at the same time

I want to use distinct & top in the same time , i did

SELECT distinct TOP 10 * FROM TableA

but i still have a duplicate PersonId so i tought to do :

SELECT distinct (personID) TOP 10 * FROM TableA but the syntax is wrong , so i wonder if there is any solution

thanks,

like image 513
user1187282 Avatar asked Mar 18 '13 14:03

user1187282


People also ask

Can we use distinct with top?

If you want to use a true DISTINCT only list out the column you want to receive distinct values of. If you have multiple columns then all those columns combined make up one distinct record. Note that without an ORDER BY this will return the first 10 records in no particular order.

Can we use top and distinct in SQL?

SQL can't apply DISTINCT() this way, but there are ways to get one row per p.id. You just need to define the requirements, and we can help...

Can you use distinct and ORDER BY together?

Without a transformation, a statement that contains both DISTINCT and ORDER BY would require two separate sorting steps-one to satisfy DISTINCT and one to satisfy ORDER BY. (Currently, Derby uses sorting to evaluate DISTINCT.

What are distinct and top keyword in SQL?

The SQL DISTINCT keyword is used in conjunction with the SELECT statement to eliminate all the duplicate records and fetching only unique records. There may be a situation when you have multiple duplicate records in a table.


2 Answers

You're using a SELECT * which is pulling in all records. If you want to use a true DISTINCT only list out the column you want to receive distinct values of. If you have multiple columns then all those columns combined make up one distinct record.

SELECT distinct TOP 10 personID  FROM TableA 

Note that without an ORDER BY this will return the first 10 records in no particular order. The results could be different each time you run the query.

like image 60
Matt Busche Avatar answered Sep 28 '22 05:09

Matt Busche


You seem to want 10 random records for different persons. Try this:

select t.* from (select t.*,              row_number() over (partition by personid order by (select NULL)) as seqnum       from t      ) t where seqnum = 1 

In general, though, when using top you should also be using an order by to specify what you mean by "top".

like image 22
Gordon Linoff Avatar answered Sep 28 '22 06:09

Gordon Linoff