我在SQL Server 2014中有一个表,如下所示:
现在我想再添加一个名为“Status”的列来标记同一个人的每一行。
我正在考虑使用:
Status = CASE
WHEN (Category = 3 AND Fee <> 0 )
OR (Category = 3 AND Fee = 0 AND (Category = 1 AND Fee <> 0))
OR (Category IN (1, 3) AND Fee = 0 AND (Category = 2 AND Fee IS NOT NULL))
THEN "Active"
ELSE "Non-Active"
END
但我不确定它是否正确。我也想知道是否有更有效的方法来实现这一结果。
答案 0 :(得分:2)
您可以使用row_number()
:
select t.*,
(case when 1 = row_number() over (partition by personid
order by (case when category = 3 and fee <> 0 then 1
when category = 1 and fee <> 0 then 2
when category = 2 then 3
else 4 end)
then 'active' else 'inactive'
end) as status
from t;