SQL Server 2008: TOP 10 and distinct together

后端 未结 13 1564
刺人心
刺人心 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-05 00:11

    I think the problem is that you want one result for each p.id?

    But you are getting "duplicate" results for some p.id's, is that right?

    The DISTINCT keyword applies to the entire result set, so applies to pl.nm, pl.val, pl.txt_val, not just p.id.

    You need something like

    SELECT TOP 10 p.id, max( p1.nm ), max (p1.val), ...
    FROM ...
    GROUP BY p.id
    

    Won't need the distinct keyword then.

提交回复
热议问题