![](/img/trans.png)
[英]How do I select one row in SQL when another row has same id but a different value in a column?
[英]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?
在SQL中,对于同一组ID,我想创建New
的Action
列,其中Contract Number
是最大的, Old
是较小的值。
例如,对于ID = 123
, Contract Number
中的最大值为 10,因此该行将标记为New
,其他行标记为Old
。 SQL 数据库中唯一的列是ID
和Contract Number
,所以我假设我应该使用CASE WHEN
语句来创建Action
列,但不确定如何制定它
样品表:
ID | 合同号码 |
---|---|
123 | 10 |
123 | 5个 |
123 | 3个 |
456 | 3个 |
456 | 2个 |
预计 output:
ID | 合同号码 | 行动 |
---|---|---|
123 | 10 | 保持 |
123 | 5个 | 老的 |
123 | 3个 | 老的 |
456 | 3个 | 保持 |
456 | 2个 | 老的 |
您可以将 case 表达式与窗口聚合一起使用:
select *,
case when
contractnumber = Max(ContractNumber) over(partition by Id) then 'Keep'
else 'Old' end Action
from sampledata;
我喜欢为此使用公用表表达式 (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.