提取Postgres中最小日期的金额

时间:2019-05-03 10:47:32

标签: postgresql

非常基本:我有一个表格,其中包含日期,帐户和该日期特定帐户所完成的金额。我遇到了一个非常基本的问题-获取每个帐户的最短日期金额。

输入:

enter image description here

所需:

enter image description here

如果我在下面的查询中进行查询,显然也会返回按金额分组。

SELECT account_ref         AS account_alias, 
       Min(timestamp_made) AS reg_date, 
       amount 
FROM   stg_payment_mysql 
GROUP  BY account_ref, 
          amount 

1 个答案:

答案 0 :(得分:1)

也许最有效的方法是使用DISTINCT ON

SELECT DISTINCT ON (account) account, date, amount
FROM stg_payment_mysql
ORDER BY account, date;

更通用的ANSI SQL方法将使用ROW_NUMBER

WITH cte AS (
    SELECT account, date, amount,
        ROW_NUMBER() OVER (PARTITION BY account ORDER BY date) rn
    FROM stg_payment_mysql
)

SELECT account, date, amount
FROM cte
WHERE rn = 1
ORDER BY account;