2017-10-04 96 views
1

我有表讓我們說table_inventory。在table_inventory我把一個觸發的股票每次更新中audit_inventory表中插入新行:獲取postgresql查詢中每個記錄的第二行最後一行

表列是什麼樣子:

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插入隨着時間一排,所以我要選擇倒數第二個股票每個inventory_id的值爲table_inventory。我寫了一些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; 

上面的查詢retrns單inventory_id的倒數第二個值,但不知道如何編寫查詢得到第二個最後一行值table_inventory的每inventory_id。

感謝您寶貴的時間。

+0

爲響應好,謝謝@VaoTsun –

+0

請提供一些數據樣本和問題,你遇到 –

+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 
相關問題