【问题标题】:How to find a record and N records before selected record in one query on PostgreSQL如何在PostgreSQL的一个查询中在选定记录之前找到一条记录和N条记录
【发布时间】:2022-01-11 19:27:50
【问题描述】:

我有一张如下表:

id name date last update
1 test1 01-01-2021 5-01-2021
2 test2 02-01-2021 6-01-2021
3 test3 03-01-2021 6-01-2021
4 test4 04-01-2021
5 test5 05-01-2021

我想进行查询以接收“上次更新”= null 的第一条记录和它之前的 2 条记录。结果应该是:

id name date last update
2 test2 02-01-2021 6-01-2021
3 test3 03-01-2021 6-01-2021
4 test4 04-01-2021

【问题讨论】:

  • 您的示例显示了 last_update = null 的第一条记录。您想要的是第一个还是最后一个?
  • @RichardHuxton “最后一次更新”为空的第一条记录(在我的示例中是 test4 )和之前的两条记录( test3 + test2 )
  • @Shadi 存在矛盾。在 Original Post 中,您说 进行查询以接收“last update” = NULL 的 LAST 记录,在回复 Richard 时,您说 FIRST 记录“last update”为空 在回答上述问题时,您在原始帖子中说 LAST 和 FIRST。因此,其中一项需求得到了纠正。

标签: sql postgresql


【解决方案1】:

您可以查找具有第一个 NULL last_update 的日期。
然后再获取该日期之前的 2。

SELECT *
FROM
(
    SELECT * 
    FROM your_table
    WHERE date <= (
      SELECT date  -- the date of the first NULL last_update
      FROM your_table 
      WHERE last_update IS NULL 
      ORDER BY date ASC NULLS LAST
      LIMIT 1
    )
    ORDER BY date DESC
    LIMIT 1+2      -- the NULL last_update + 2 records before it
) q
ORDER BY date ASC;
id name date last_update
3 test2 2021-01-02 2021-01-06
4 test3 2021-01-03 2021-01-06
5 test4 2021-01-04 null

dbfiddle here

上的演示

【讨论】:

  • 太好了,这很好。澄清一下,q 是什么?
  • 只是子查询的短别名。一些数据库风格需要它,所以我有这个习惯来添加它。 q 是查询的缩写。
【解决方案2】:

使用这个:

select * from yourTable where lastUpdate=(select Max(lastUpdate) from yourTable)
Union all 
select id,name,date,lastUpdate from 
    (select *,ROW_NUMBER() over (partition by lastUpdate order by id)as rn from yourTable where lastUpdate is null )a where rn=1

输出:

id  name    date    lastUpdate
2   test2   2021-02-01  2021-06-01
3   test3   2021-03-01  2021-06-01
4   test4   2021-04-01  NULL

【讨论】:

  • 感谢我运行此查询,但我收到了样本中测试之前的所有记录。例如,如何限制两条记录?
  • 此查询将为您提供的数据提供一个很好的答案。因此,在这种情况下,您必须提供大量数据。
【解决方案3】:

here 所述,使用“with”语句的更简单的解决方案。

WITH dat AS 
  (SELECT ID FROM records WHERE last_update ISNULL ORDER BY ID LIMIT 1)   --Finding the first null

SELECT r.* 
FROM
    records r, dat 
WHERE
    r.ID BETWEEN ( dat.ID - 2 ) AND dat.ID                              --Finding 2 records before
ORDER BY r.ID;

【讨论】:

  • 你能解释一下什么是“r”吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-07
  • 2015-10-09
相关资源
最近更新 更多