作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个派生表,其中包含如下列:
如何在 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/
我正在尝试开发右边框/Angular 具有特定 Angular (30°) 的表格。我见过一些类似的解决方案,但它们都无法在一定程度上发挥作用。如果我想从 30° 改变到 20°,我不想花太多力气。
我是一名优秀的程序员,十分优秀!