sql-server-2005 - SQL Server选择不同的最新值

标签 sql-server-2005 select join distinct

我有一个表,其中有很多行(> 10K)。大多数行具有与用户名相关联的重复角色值。

我想做的是选择由 request_id 添加的不同且最新的角色选择行。
我几乎拥有它,但是让我大吃一惊的部分是,某些 request_id 字段中包含null值,因为这些请求是在添加该列之前发出的。我 STILL 需要将它们包括在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()不计算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

最佳答案

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

关于sql-server-2005 - SQL Server选择不同的最新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16966415/

相关文章:

sql-server-2005 - SQL Server 2005中手动实现的Identity列

sql - Access 查询返回空字段,具体取决于表的链接方式

mysql - 使用 mysql 连接和 2 个表获取记录总数

MySQL 查询自连接最大日期

c# - Sql-server 2005 中的内部连接问题

sql - 关闭winform应用程序、自动保存选项后sql server中的数据丢失

mysql - MySQL的SELECT WHERE如何进行整数比较?

mysql - 检查两个表中的缺失值

mysql - 获取最新记录

mysql - 按类型返回每个月的用户数