如何在一个组中仅将一行标记为“活动”,并在特定条件下共享相同的ID

时间:2017-01-10 22:41:52

标签: sql-server case-when

我在SQL Server 2014中有一个表,如下所示:

sample table

现在我想再添加一个名为“Status”的列来标记同一个人的每一行。

  • 如果Category = 3且Fee<> 0然后将此行标记为“活动”,其余部分(1和2)将“非活动”;
  • 如果Category = 3且Fee = 0,则它移动到Category = 1,其中Fee<> 0并将其设为“活动”,然后其余部分(2,3)将“非活动”;
  • 如果Category = 3和1且两个Fee = 0,则将最后一个(Category = 2)标记为“Active”,无论2类费用= 0 /<> 0。

我正在考虑使用:

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

但我不确定它是否正确。我也想知道是否有更有效的方法来实现这一结果。

1 个答案:

答案 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;