我有一个派生表,其中包含如下列:
- 电子邮件(主要标识符)
- 交易时间
- 数量
如何在 PostgreSQL 中根据第一笔交易的 amount > 500
寻找客户(通过电子邮件识别)?
注意:这用于过滤主表的子查询。
最佳答案
下面的解决方案将比 Postgres 特定的 DISTINCT ON
更具可移植性。使用 row_number()
枚举行并获取其首次交易金额大于 500 的所有不同客户(通过电子邮件标识)。
编辑:我提供了三种方法来实现相同的结果。选择您喜欢的任何一个。
第一种方法 - 使用 row_number()
select
distinct email
from (
select
email,
amount,
row_number() OVER (PARTITION BY email ORDER BY transaction_time) AS rn
from <derived_table_here>
) t
where
rn = 1
and amount > 500
第二种方法 - 使用 DISTINCT ON
select
email
from (
select distinct on (email)
email,
amount
from <derived_table_here>
order by email, transaction_time
) t
where amount > 500
第三种方法 - 使用 NOT EXISTS
select
email
from <derived_table_here> t1
where
amount > 500
and not exists(
select 1
from <derived_table_here> t2
where
t1.email = t2.email
and t1.transaction_time > t2.transaction_time
)
我发现第三种方法最可移植,因为例如 MySQL 不支持窗口函数,AFAIK。这只是为了防止将来在数据库之间切换 - 减少您的工作量。
在以下示例中测试:
email | transaction_time | amount
-----------------+----------------------------+--------
first@mail.com | 2016-09-26 19:01:15.297251 | 400 -- 1st, amount < 500
first@mail.com | 2016-09-26 19:01:19.160095 | 500
first@mail.com | 2016-09-26 19:01:21.526307 | 550
second@mail.com | 2016-09-26 19:01:28.659847 | 600 -- 1st, amount > 500
second@mail.com | 2016-09-26 19:01:30.292691 | 200
second@mail.com | 2016-09-26 19:01:31.748649 | 300
third@mail.com | 2016-09-26 19:01:38.59275 | 200 -- 1st, amount < 500
third@mail.com | 2016-09-26 19:01:40.833897 | 100
fourth@mail.com | 2016-09-26 19:01:51.593279 | 501 -- 1st, amount > 500
关于sql - 找出第一个超过一定值的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39708113/