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,
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.
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...
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.
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.
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.
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".
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