SQL Server 2008: TOP 10 and distinct together

后端 未结 13 1607
刺人心
刺人心 2021-02-04 23:41

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:

13条回答
  •  时光取名叫无心
    2021-02-04 23:50

    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.

提交回复
热议问题