[英]Select only one row when a certain condition is met?
ID ![]() |
NAME![]() |
DATE![]() |
STATUS![]() |
---|---|---|---|
1 ![]() |
Joe![]() |
01-22 ![]() |
Approved![]() |
1 ![]() |
Joe![]() |
01-22 ![]() |
Pending![]() |
2 ![]() |
Bill![]() |
02-22 ![]() |
Approved![]() |
2 ![]() |
Bill![]() |
02-22 ![]() |
Sent back![]() |
3 ![]() |
John![]() |
01-22 ![]() |
Approved![]() |
4 ![]() |
Bob![]() |
02-22 ![]() |
Pending![]() |
How do I only return one row per ID, placing priority on approved?如何每个 ID 只返回一行,优先考虑已批准?
Example: for Id 1 I only want the row that is approved and not the one that is pending.示例:对于 ID 1,我只想要已批准的行,而不是待处理的行。
Some Id's may only have 1 record for example ID 4 has just one record and is pending.一些 ID 可能只有 1 条记录,例如 ID 4 只有一条记录并且处于待处理状态。
What I want is: IF status = approved and pending for the same Id then keep the approved record and not select the pending record我想要的是:如果状态 = 相同 ID 的已批准和待处理,则保留已批准的记录,而不是 select 待处理记录
If status = pending then keep that record如果 status = pending 则保留该记录
This will preferentially select Approved, then Pending, then everything else.这将优先 select Approved,然后是 Pending,然后是其他所有内容。 If you don't want "everything else" just filter in the WHERE clause.
如果您不想要“其他所有内容”,只需在 WHERE 子句中进行过滤。
select id,
name,
date,
status
from (
select *,
row_number() over
( partition by id
order by case when status = 'Approved' then 1
when status = 'Pending' then 2
else 3
end asc,
date
) as first_by_date_with_approved_precedence
from your_table
) tmp
where first_by_date_with_approved_precedence = 1
It could also be as easy as the following (provided status is not blank or null)它也可以像下面这样简单(前提是状态不是空白或空)
Select Top 1 with ties *
from YourTable
order by row_number() over (partition by id order by Status)
Results结果
ID NAME DATE STATUS
1 Joe 01-22 Approved
2 Bill 02-22 Approved
3 John 01-22 Approved
4 Bob 02-22 Pending
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.