繁体   English   中英

对于SQL一列中的相同ID,如何为另一列中值较大的行编写Case语句?

[英]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,我想创建NewAction列,其中Contract Number是最大的, Old是较小的值。

例如,对于ID = 123Contract Number中的最大值为 10,因此该行将标记为New ,其他行标记为Old SQL 数据库中唯一的列是IDContract 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

output: 输出

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM