Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2008: TOP 10 and distinct together

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.

like image 950
user327301 Avatar asked Dec 17 '09 22:12

user327301


People also ask

Can we use distinct and top together in SQL?

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.

How do I get top 10 distinct records in SQL Server?

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.

Can you use distinct and ORDER BY together?

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).

How do I get unique combinations in SQL?

Simply use the DISTINCT keyword: SELECT DISTINCT Latitude, Longitude FROM Coordinates; This will return values where the (Latitude, Longitude) combination is unique.


1 Answers

Try

SELECT TOP 10 distinct MyId FROM sometable; 
like image 100
Halim Avatar answered Sep 28 '22 17:09

Halim