在分组行中挑选第一个实例 - PostgreSQL

时间:2015-11-03 06:59:07

标签: sql postgresql greatest-n-per-group

这是背景,我有一组行:

enter image description here

我只希望在每个accountid类型列中的每次RECOVERY之后获得第一个ADVANCE

所以我的结果应该是procdates的进展

2015-09-03 09:55:12.228343
2015-09-04 23:10:42.016903

这可以在一个查询中使用吗?

2 个答案:

答案 0 :(得分:0)

试试这个:

WITH CTE_PrevType
AS (
    SELECT accountid
        ,procdate
        ,LAG(type, 1, NULL) OVER (
            ORDER BY procdate
            ) AS PreviousType
    FROM < Table_Name >
    )
SELECT
accountid
,procdate
,type
,value
FROM < Table_Name > AS TN
INNER JOIN CTE_PrevType CPT
    ON TN.accountid = CPT.accountid
        AND TN.procdate = CPT.procdate
WHERE TN.type = 'ADVANCE'
    AND CPT.type = 'RECOVERY'

答案 1 :(得分:0)

我找到了如何获得它!

SELECT * FROM
(SELECT accountid,
    procdate, 
        type, 
        value, 
        LAG(type) OVER (ORDER BY procdate ASC) AS previousType
   FROM transaction) w WHERE previousType = 'RECOVERY';