簡體   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