我有一個結構如下的表:
order_yr acct_id indv_id age
2019 323 01 38
2019 323 02 37
2019 323 03 16
2019 323 04 5
2019 325 01 38
2019 326 01 64
2019 326 02 63
如果 order_yr 和 acct_id 的某人年齡 <=17,我需要做的是通過 order_yr 和 acct_id 添加一個標志。
結果將是這樣的:
order_yr acct_id indv_id age child_flg
2019 323 01 38 1
2019 323 02 37 1
2019 323 03 16 1
2019 323 04 5 1
2019 325 01 38 0
2019 326 01 64 0
2019 326 02 63 0
我知道我必須按 order_yr 和 acct_id 進行磁區,但不確定如何在一個行內腳本中獲得結果。
任何幫助,將不勝感激。
順便說一句,這是一個單獨的級別提取,其中包含與每個 indv 關聯的許多其他列。
我還沒有走得很遠 - 我有這個:
,ROW_NUMBER() OVER(PARTITION BY order_yr, acct_id ORDER BY (CASE WHEN age <=17 THEN 'Y' ELSE 'N' END) desc) AS CHILD_flg
uj5u.com熱心網友回復:
你在這里有一些選擇。一種是使用子查詢來確定是否存在屬于某個組并滿足您的條件的行:
select *
, case
when exists (select *
from #data sub
where sub.order_yr = d.order_yr
and sub.acct_id = d.acct_id
and sub.age <= 17)
then 1
else 0
end as flag
from #data d
您也可以像您計劃的那樣使用視窗功能:
select *
, max(case when age <= 17 then 1 else 0 end) over (partition by order_yr, acct_id) as flag
from #data d
dbfiddle 上的作業演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/435473.html
