[英]For the same ID in one column of SQL, how do I write a Case statement for the row with the greater value in the another column?
In SQL, for the same set of ID, I want to create the column Action
with New
where the Contract Number
is the largest and Old
for the smaller values.在SQL中,对于同一组ID,我想创建
New
的Action
列,其中Contract Number
是最大的, Old
是较小的值。
For example, for ID = 123
, the largest value in Contract Number
is 10, so that row will be marked as New
and the others as Old
.例如,对于
ID = 123
, Contract Number
中的最大值为 10,因此该行将标记为New
,其他行标记为Old
。 The only columns in the SQL database are ID
and Contract Number
, so I'm assuming I should use a CASE WHEN
statement to create the Action
column, but not sure how to formulate it SQL 数据库中唯一的列是
ID
和Contract Number
,所以我假设我应该使用CASE WHEN
语句来创建Action
列,但不确定如何制定它
Sample table:样品表:
ID ![]() |
Contract Number![]() |
---|---|
123 ![]() |
10 ![]() |
123 ![]() |
5 ![]() |
123 ![]() |
3 ![]() |
456 ![]() |
3 ![]() |
456 ![]() |
2 ![]() |
Expected output:预计 output:
ID ![]() |
Contract Number![]() |
Action![]() |
---|---|---|
123 ![]() |
10 ![]() |
Keep![]() |
123 ![]() |
5 ![]() |
Old![]() |
123 ![]() |
3 ![]() |
Old![]() |
456 ![]() |
3 ![]() |
Keep![]() |
456 ![]() |
2 ![]() |
Old![]() |
You could use a case expression together with a windowed aggregate:您可以将 case 表达式与窗口聚合一起使用:
select *,
case when
contractnumber = Max(ContractNumber) over(partition by Id) then 'Keep'
else 'Old' end Action
from sampledata;
I like using Common Table Expressions (CTEs) for this我喜欢为此使用公用表表达式 (CTE)
--get the max value
;with CN as (select max(ContractNumber) as MaxContractNumber, ID
FROM [SampleDb].[dbo].[SampleDataforSO]
group by ID,ContractNumber)
--loop through and assign the relevant action item for the max value
select s.ID, s.ContractNumber,
case
when ContractNumber < max(MaxContractNumber) then 'Old'
when ContractNumber = max(MaxContractNumber) then 'Keep'
end as 'Action'
from CN
join [SampleDb].[dbo].[SampleDataforSO] s
on s.ID = cn.ID
group by s.id, ContractNumber
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.