获取postgresql查询中每条记录的倒数第二行

时间:2017-10-04 12:30:09

标签: postgresql postgresql-9.4

我有桌子让我们说table_inventory。在table_inventory上,我为audit_inventory表中每次更新库存插入新行设置了一个触发器:

表格列如下所示:

table_inventory

| sr_id | inventory_id | p_name |股票|

audit_inventory

| insert_time || sr_id | inventory_id | p_name |股票|

现在我的问题是 table_inventory 的每个inventory_id在 audit_inventory 中有多个条目,因为我为每次更新库存时添加触发器在中插入一行时间audit_inventory ,所以我想为 table_inventory 的每个inventory_id选择第二个最后库存值。我写了一些cte来做到这一点,但无法获得每个inventory_id。

 WITH CTE as
    (select inventory_id,stock from table_inventory),
cte_1 as(
      SELECT
        stock,
        row_number() over (order by insert_time desc) rn
      FROM audit_inventory where inventoryid in (select inventory_id from cte)
    ),cte_2 as(
    SELECT stock
    FROM CTE
    WHERE rn = 2)
select * from cte,cte_1;

以上查询会查找单个inventory_id的倒数第二个值,但不了解如何编写查询以获取 table_inventory 的每个inventory_id的第二个最后一行值。

感谢您宝贵的时间。

1 个答案:

答案 0 :(得分:1)

尝试这样做。我想这就是你想要的:

WITH CTE as
( SELECT
        stock,
        inventory_id,
        row_number() over (PARTITION BY inventoryid order by insert_time desc) rn
  FROM audit.inventory 
)

SELECT
    CTE.stock,
    ti.inventory_id,
    ti.stock
FROM
    table_inventory ti
    inner join CTE on CTE.inventory_id=ti.inventory_id
WHERE
     CTE.rn=2