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 from(select distinct p.id from tablename)tablename
well I wouldn't have expected it, but Halim's SELECT distinct TOP 10 MyId FROM sometable
is functionally identical to Vaishnavi Kumar's select top 10 p.id from(select distinct p.id from tablename)tablename
create table #names ([name] varchar(10))
insert into #names ([name]) values ('jim')
insert into #names ([name]) values ('jim')
insert into #names ([name]) values ('bob')
insert into #names ([name]) values ('mary')
insert into #names ([name]) values ('bob')
insert into #names ([name]) values ('mary')
insert into #names ([name]) values ('john')
insert into #names ([name]) values ('mark')
insert into #names ([name]) values ('matthew')
insert into #names ([name]) values ('luke')
insert into #names ([name]) values ('peter')
select distinct top 5 [name] from #names
select top 5 * from (select distinct [name] from #names) subquery
drop table #names
produces the same results for both selects:
name
1 bob
2 jim
3 john
4 luke
5 mark
it's curious that select top 5 distinct is not valid, but select distinct top 5 is and works as you might expect select top 5 distinct to work.
Try
SELECT TOP 10 distinct MyId FROM sometable;
Few ideas:
Try something like this:
SELECT DISTINCT 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
ORDER BY pl.nm
Note that i commented out some of the SELECT to limit your result set and DISTINCT logic.
I know this thread is old, but figured I would throw in what came up with since I just ran into this same issue. It may not be efficient, but I believe it gets the job done.
SELECT TOP 10 p.id, pl.nm, pl.val, pl.txt_val
INTO #yourTempTable
from dm.labs pl
join mas_data.patients p on pl.id = p.id
where pl.nm like '%LDL%' and val is not null
select p.id, pl.nm, pl.val, pl.txt_val
from #yourTempTable
where id IN (select distinct id from #yourTempTable)
DISTINCT
removes rows if all selected values are equal. Apparently, you have entries with the same p.id
but with different pl.nm
(or pl.val
or pl.txt_val
). The answer to your question depends on which one of these values you want to show in the one row with your p.id
(the first? the smallest? any?).