我有一个表,其中有很多行(> 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/