sql—使用order by从数据库中检索每个组中的最后一条记录

fivyi3re  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(320)

有一张table ticket 包含如下数据:

Id   Impact   group        create_date
------------------------------------------
1     3        ABC       2020-07-28 00:42:00.0
1     2        ABC       2020-07-28 00:45:00.0
1     3        ABC       2020-07-28 00:48:00.0
1     3        ABC       2020-07-28 00:52:00.0
1     3        XYZ       2020-07-28 00:55:00.0
1     3        XYZ       2020-07-28 00:59:00.0

预期结果:

Id   Impact   group        create_date
------------------------------------------
1     3        ABC       2020-07-28 00:42:00.0
1     2        ABC       2020-07-28 00:45:00.0
1     3        ABC       2020-07-28 00:52:00.0
1     3        XYZ       2020-07-28 00:59:00.0

目前,我使用的查询是:

WITH final AS (
    SELECT p.*, 
           ROW_NUMBER() OVER(PARTITION BY p.id,p.group,p.impact
                                 ORDER BY p.create_date desc, p.impact) AS rk
      FROM ticket p 
)
SELECT f.*
  FROM final f 
 WHERE f.rk = 1

结果是:

Id   Impact    group         create_date
-----------------------------------------
1     2        ABC       2020-07-28 00:45:00.0
1     3        ABC       2020-07-28 00:52:00.0
1     3        XYZ       2020-07-28 00:59:00.0

似乎分区比按值排序优先。有没有其他方法可以达到预期的效果。我正在amazon redshift上运行这些查询。

xzlaal3s

xzlaal3s1#

你好像想要排在哪里 id / impact / group 相对于下一行更改。一个简单的方法是看下一个 create_date 总体和下一步 create_date 为了团队。如果它们相同,则过滤:

select t.*
from (select t.*,
             lead(create_date) over (order by create_date) as next_create_date,
             lead(create_date) over (partition by id, impact, group order by create_date) as next_create_date_img
      from ticket t
     ) t
where next_create_date_img is null or next_create_date_img <> next_create_date;
0yycz8jy

0yycz8jy2#

你可以用 LEAD() 检查 Impact 在行之间更改,只取值将更改的行。

WITH
  look_forward AS
(
  SELECT
    *,
    LEAD(impact) OVER (PARTITION BY id, group ORDER BY create_date) AS lead_impact
  FROM
    ticket
)
SELECT
  *
FROM
  look_forward 
WHERE
     lead_impact IS NULL
  OR lead_impact <> impact

相关问题