SQL Server 2008: TOP 10 and distinct together

后端 未结 13 1837
刺人心
刺人心 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:54

    Few ideas:

    1. You have quite a few fields in your select statement. Any value being different from another will make that row distinct.
    2. TOP clauses are usually paired with WHERE clauses. Otherwise TOP doesn't mean much. Top of what? The way you specify "top of what" is to sort by using WHERE
    3. It's entirely possible to get the same results even though you use TOP and DISTINCT and WHERE. Check to make sure that the data you're querying is indeed capable of being filtered and ordered in the manner you expect.

    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.

提交回复
热议问题