非常基本:我有一个表格,其中包含日期,帐户和该日期特定帐户所完成的金额。我遇到了一个非常基本的问题-获取每个帐户的最短日期金额。
输入:
所需:
如果我在下面的查询中进行查询,显然也会返回按金额分组。
SELECT account_ref AS account_alias,
Min(timestamp_made) AS reg_date,
amount
FROM stg_payment_mysql
GROUP BY account_ref,
amount
答案 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;