SQL Server 2008: TOP 10 and distinct together

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

    You could use a Common Table Expression to get the top 10 distinct ID's and then join those to the rest of your data:

    ;WITH TopTenIDs AS
    ( 
       SELECT DISTINCT TOP 10 id
       FROM dm.labs 
       ORDER BY ......
    )
    SELECT 
        tti.id, pl.nm, pl.val, pl.txt_val
    FROM
        TopTenIDs tti
    INNER JOIN
        dm.labs pl ON pl.id = tti.id
    INNER JOIN 
        mas_data.patients p ON pl.id = p.id
    WHERE
        pl.nm like '%LDL%'
        AND val IS NOT NULL
    

    That should work. Mind you: if you have a "TOP x" clause, you typically also need an ORDER BY clause - if you want the TOP 10, you need to tell the system in what order that "TOP" is.

    PS: why do you even join the "patients" table, if you never select any fields from it??

提交回复
热议问题