【问题标题】:SQL Server select distinct latest valuesSQL Server 选择不同的最新值
【发布时间】:2013-06-06 15:41:32
【问题描述】:

我有一个包含大量行 (>10K) 的表。大多数行都有与 username 相关联的重复 role 值。

我想要做的是通过 request_id 添加的不同和最新的 role 选择行。 我几乎拥有它,但让我大吃一惊的是,某些 request_id 字段中有null 值,因为这些请求是在添加该列之前发出的。我仍然需要将它们包含在 select statement 中,以防用户在更新后没有输入其他请求。

这里是我的表结构示例:

 id | uname  | role    | request_id
 0  | jsmith  | User   | null
 1  | jsmith  | Admin   | null
 2  | jsmith  | Dude    | null
 3  | jsmith  | Admin   | 56
 4  | jsmith  | Dude    | 56
 5  | jsmith  | Admin   | 57
 6  | jsmith  | Dude    | 57

这将是期望的结果:

0  | jsmith  | User    | null
5  | jsmith  | Admin   | 57
6  | jsmith  | Dude    | 57

以下是我目前尝试过的陈述:

加入

select distinct a.uname, a.role, a.request_id from (
    select * from  das_table 
    ) 
b join das_table a on b.role = a.role and b.request_id = a.request_id
where a.uname = 'jsmith'

结果:这消除了 request_id = NULL

的行

MAX()

我猜这对我不起作用,因为 MAX() 不计算 null 值?

select distinct uname, role, max(request_id) as request_id from das_table where uname='jsmith'
group by uname, role, request_id

我看过的类似问题:

在我的问题中,我认为与我研究过的其他问题不同的是,request_id 有可能为空。

Select distinct values from 1 column | SQL Server : select distinct by one column and by another column value | SQL Server select distinct hell

【问题讨论】:

    标签: sql-server-2005 select join distinct


    【解决方案1】:

    max 查询无效,因为您将 request_id 包含在分组中 - 尝试:

    select distinct uname, role, max(request_id) as request_id 
    from das_table where uname='jsmith'
    group by uname, role
    

    SQLFiddle here.

    【讨论】:

    • @ckpepper02:很高兴我能帮上忙。
    • 我不确定这里是否需要 distinct 子句,因为您使用的是 group by
    【解决方案2】:

    似乎 ISNULL 可以解决您的问题,为了简单起见,我在这里使用 1,但如果这对您的使用更有意义,您可以使用 -1。

    MAX(ISNULL(request_id, 1))
    

    【讨论】: