我的结果集如下所示:
ID Pass DESCRIPTION DATE STATUS
123 3455 RUNNING 13/09/2017 INSERTED
123 3455 RUNNING 14/09/2017 INSERTED
123 3455 RUNNING 15/09/2017 INSERTED
123 3455 RUNNING 16/09/2017 INSERTED
123 3455 RUNNING 17/09/2017 DELETED
123 3455 JUMPING 17/09/2017 INSERTED
123 3455 JUMPING 17/09/2017 DELETED
456 8968 JUMPING 18/09/2017 INSERTED
456 8968 JUMPING 18/09/2017 DELETED
456 8968 JUMPING 06/10/2017 INSERTED
456 8968 JUMPING 07/10/2017 INSERTED
456 8968 JUMPING 08/10/2017 INSERTED
456 8968 JUMPING 09/10/2017 RETIRADO
我希望从这个结果集中获得:
ID Pass DESCRIPTION DATE STATUS
123 3455 RUNNING 13/09/2017 INSERTED
123 3455 RUNNING 17/09/2017 DELETED
123 3455 JUMPING 17/09/2017 INSERTED
123 3455 JUMPING 17/09/2017 DELETED
456 8968 JUMPING 18/09/2017 INSERTED
456 8968 JUMPING 18/09/2017 DELETED
456 8968 JUMPING 06/10/2017 INSERTED
456 8968 JUMPING 09/10/2017 RETIRADO
这些事件的最小和最大日期,忽略最小值和最大值内的所有日期。 ID,Pass和DESCRIPTION可以相同,但是当STATUS发生变化时,我希望得到最小和最大结果。有人能帮助我吗?
答案 0 :(得分:0)
尝试使用以下
;WITH CTE
AS
(
SELECT
RN = ROW_NUMBER() OVER(PARTITION BY ID,Pass,Description,Status ORDER BY Date ASC),
*
FROM T1
)
SELECT
*
FROM CTE
WHERE RN = 1
检查Demo此处
答案 1 :(得分:0)
您可以使用lag
获取相关结果集。
select *
from (select t.*,lag(status) over(partition by id order by date_column) as prev_status
from tbl t
) t
where prev_status is null or prev_status <> status
编辑:由于给定日期有多行,您应指定一列以便可靠地排序行。
使用lag(status) over(partition by id order by date_column,other_order_column)
获得一致的结果。