确定“活动”记录

时间:2017-05-08 17:09:36

标签: sql-server

我列出了可以列出单个或多个服务的客户列表。在随时间变化的表格中,存在“已添加”或“已删除”的指示。 我需要的是:确定当前有效的服务(如果有的话)。 以下是一组示例数据:

CUST_ID SRV_ID  STATUS  ACTION_DATE
12345   102 Added   1/31/17 10:15
12345   189 Added   4/18/17 15:37
12345   189 Removed 4/21/17 14:08
12345   194 Added   5/2/17 14:43
12345   194 Removed 5/5/17 10:02
12345   194 Added   5/5/17 13:06
12345   69  Added   4/19/17 9:36
12345   69  Removed 5/2/17 14:43
12345   73  Added   4/20/17 10:21
12345   73  Removed 4/25/17 11:20
12345   95  Added   5/4/17 9:48
12345   95  Removed 5/4/17 10:05

要返回的记录:102年1月31日10:15和194年5月5日17:06

2 个答案:

答案 0 :(得分:0)

您可以使用top 1 with ties和窗口函数row_number找到每个cust_id和serv_id的最新行,然后过滤状态为&#34的最新行;添加":

select *
from (
    select top 1
    with ties *
    from your_table
    order by row_number() over (
            partition by cust_id, srv_id
            order by action_date desc
            )
    ) t
where status = 'Added'

产地:

CUST_ID SRV_ID  STATUS  ACTION_DATE
12345   102     Added   2017/01/31 10:15
12345   194     Added   2017/05/05 13:06

Demo

答案 1 :(得分:0)

像这样:

SELECT SRV_ID
FROM YourTable
GROUP BY SRV_ID
HAVING MAX(CASE WHEN STATUS='Added' THEN ACTION_DATE END)
     > MAX(CASE WHEN STATUS='Removed' THEN ACTION_DATE END)