下面是一张表:
ID& amp;当Role = Red
时捕获MAX
值的行
ID Role HistID Date Style
1 Yellow 101 1/1/17 M
1 Red 101 1/2/17 F
1 Red (Null) 1/5/17 C
2 Blue 101 5/1/17 a
2 Yellow 201 4/1/17 b
2 Red 301 5/5/17 C
3 Yellow (Null)
引用以下行:
ID Role HistID Date Style
1 Red (Null) 1/5/17 c
2 Red 301 5/5/17 c
现在基于这些行应用条件。
WHEN HistID IS NOT NULL and Style = C THEN 'Assigned'
ELSE'Unassigned'
END Status
输出:
ID Role HistID Date Style Status
1 Yellow 101 1/1/17 M Unassigned
1 Red 101 1/2/17 F Unassigned
1 Red (Null) 1/5/17 C Unassigned
2 Blue 101 5/1/17 a Assigned
2 Yellow 201 4/1/17 b Assigned
2 Red 301 5/5/17 C Assigned
3 Yellow (Null) Unassigned
这里的答案不是很多,我想了解并学习应用MAX
,Case Expression
和Keep
子句背后的语法。
答案 0 :(得分:0)
使用窗口功能:
select t.*,
(case when matches_flag > 0 then 'Assigned' else 'Unassigned' end) as status
from (select t.*,
sum(case when role = 'Red' and histid is not null and style = 'C' then 1 else 0 end) over
(partition by id) as matches_flag
from t
) t;
编辑:
实际上并不需要子查询。我只是认为它使逻辑更容易遵循。你可以这样做:
select t.*,
(case when sum(case when role = 'Red' and histid is not null and style = 'C' then 1 else 0 end) over (partition by id) > 0
then 'Assigned'
else 'Unassigned'
end) as status
from t;