![](/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.