我有一个包含大量行(> 10K)的表。大多数行都有重复role与相关的值username.
我想做的是按不同和最新选择行role添加者请求ID。
我几乎已经拥有了,但是让我感到不安的部分是null
某些值请求ID字段,因为这些请求是在添加该列之前发出的。我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
以下是我迄今为止尝试过的声明:
Join
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'
Result:这消除了行请求ID = NULL
MAX()
我想这对我不起作用,因为MAX()
不算数null
values?
select distinct uname, role, max(request_id) as request_id from das_table where uname='jsmith'
group by uname, role, request_id
我看过的类似问题:
我认为我的问题中的一个警告与我研究过的其他问题不同的是request_id
有可能为空。
从 1 列中选择不同的值 https://stackoverflow.com/questions/1918556/sql-select-distinct-values-from-1-column |
SQL Server:按一列和另一列值选择不同的值 https://stackoverflow.com/questions/13461902/sql-server-select-distinct-by-one-column-and-by-another-column-value |
SQL Server 选择不同的地狱 https://stackoverflow.com/questions/2247401/sql-server-select-distinct-hell