As the title says, I'm using SQL Server 2008. Apologies if this question is very basic. I've only been using SQL for a few days. Right now I have the following query:
SELECT TOP 10 p.id, pl.nm, pl.val, pl.txt_val from dm.labs pl join mas_data.patients p on pl.id = p.id where pl.nm like '%LDL%' and val is not null
What I want to do is use select top n together with distinct values in the id column. Searching through some forums says to use
SELECT DISTINCT TOP 10 ...
but when I replace the first line with
SELECT DISTINCT TOP 10 p.id, pl.nm, pl.val, pl.txt_val
I get the same results as without the word distinct. What should I be doing to only get to filter out duplicate id entries?
Thank you.
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.
To do so, select Query -> Include Actual Query Plan from the menu before executing the query. The “Stream Aggregate” icon is for the DISTINCT operation and “Top” for the TOP 10 one. It may seem somewhat counterintuitive to see DISTINCT listed first within the SELECT statement.
All titles are distinct. There is no way this query can be executed reasonably. Either DISTINCT doesn't work (because the added extended sort key column changes its semantics), or ORDER BY doesn't work (because after DISTINCT we can no longer access the extended sort key column).
Simply use the DISTINCT keyword: SELECT DISTINCT Latitude, Longitude FROM Coordinates; This will return values where the (Latitude, Longitude) combination is unique.
Try
SELECT TOP 10 distinct MyId FROM sometable;
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