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, 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

What I want to do is use select top n together with distinct values in the id column. Searching through some forums says to use

SELECT DISTINCT TOP 10 ...

but when I replace the first line with

SELECT DISTINCT TOP 10 p.id, pl.nm, pl.val, pl.txt_val

I get the same results as without the word distinct. What should I be doing to only get to filter out duplicate id entries?

Thank you.

推荐答案

The easy option is to use group by and select min/max for all other fields

SELECT TOP 10 
    p.id, 
    max(pl.nm),
    max(pl.val),
    max(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
group by 
    p.id

This can get quite tedious for wide table so the other option is to use rank over and partiion

SELECT TOP 10 
    p.id, 
     pl.nm, 
     pl.val, 
   pl.txt_val, 
    rank() over(partition by p.id order by p.id) as Rank
from 
    dm.labs pl
join 
    mas_data.patients p    
on 
    pl.id = p.id
  where 
    pl.nm like '%LDL%'
and 
    val is not null
and
    Rank = 1

Sql相关问答推荐

如何并行SELECT和RESET?

使用交叉应用透视表在SQL中转换分段时间段&

如何使用PostGIS从单个表中 Select 所有相交面组

如何使用WSO2将空值传递给我的SQL Server存储过程?

按每天的最大值分组

使用列表作为参数进行 Select ,如果为空,则在PostgreSQL中不使用参数进行 Select

从包含PostgreSQL中的JSON值的列中提取列表或目录

组合2个分区表的postgres视图的执行计划正在访问所有分区

Proc SQL Select Distinct SAS

同时插入和更新记录

使用 SQL 将列添加到 Access 数据库时出错

如何使用最后一个非 NULL 值在 PostgreSQL 列中填充 NULL 值

什么是 100.它与 100 有什么区别?

获取所有用户的第一次和最后一次发货以及到达日期

如何在TSQL中编写此窗口查询

SQL 按 id 运行总计并受条件限制(在窗口上)

Select 字段,除非另一个字段包含重复项

SQL日期比较用例;月初至今的报告

SQL 计数和过滤查询优化

遍历数据,计算每个月最后三天的总和