获取每个类别的最新状态
Get most recent status for each category
我遇到了这个有趣的问题。我有一个名为 email_track
的 table 来跟踪每个类别的电子邮件状态,比如(邀请、时事通讯)
这是我的 table 数据的样子,
通过以下查询,我可以获得每个 to_email
、
的最新记录
with `et2` as (
select `et1`.`category`, `et1`.`to_email`, `et1`.`subject`, `et1`.`status`, ROW_NUMBER() OVER (partition by `to_email` order by `id` desc) as `rn`
from `email_track` `et1`
)
select * from `et2` where `rn` = 1;
select `et1`.`category`, `et1`.`to_email`, `et1`.`subject`, `et1`.`status`, `et2`.`id`
from `email_track` `et1`
left join `email_track` `et2` on (`et1`.`to_email` = `et2`.`to_email` and `et1`.`id` < `et2`.`id`)
where `et2`.`id` is null;
我期待的是电子邮件 john@example.com
我应该得到两条记录,一条是类别邀请,另一条是时事通讯。现在,我们不会得到那个结果,因为我们按 to_email
分区
I should get two records one for category invitation and the other for the newsletter. Now, we won't get that result since we partition by to_email
.
将 category
添加到 window 函数的 partition by
子句应该足以提供您想要的结果:
with et2 as (
select et1.category, et1.to_email, et1.subject, et1.status,
row_number() over(partition by to_email, category order by id desc) as rn
from email_track et1
)
select * from et2 where rn = 1;
我遇到了这个有趣的问题。我有一个名为 email_track
的 table 来跟踪每个类别的电子邮件状态,比如(邀请、时事通讯)
这是我的 table 数据的样子,
通过以下查询,我可以获得每个 to_email
、
with `et2` as (
select `et1`.`category`, `et1`.`to_email`, `et1`.`subject`, `et1`.`status`, ROW_NUMBER() OVER (partition by `to_email` order by `id` desc) as `rn`
from `email_track` `et1`
)
select * from `et2` where `rn` = 1;
select `et1`.`category`, `et1`.`to_email`, `et1`.`subject`, `et1`.`status`, `et2`.`id`
from `email_track` `et1`
left join `email_track` `et2` on (`et1`.`to_email` = `et2`.`to_email` and `et1`.`id` < `et2`.`id`)
where `et2`.`id` is null;
我期待的是电子邮件 john@example.com
我应该得到两条记录,一条是类别邀请,另一条是时事通讯。现在,我们不会得到那个结果,因为我们按 to_email
分区
I should get two records one for category invitation and the other for the newsletter. Now, we won't get that result since we partition by
to_email
.
将 category
添加到 window 函数的 partition by
子句应该足以提供您想要的结果:
with et2 as (
select et1.category, et1.to_email, et1.subject, et1.status,
row_number() over(partition by to_email, category order by id desc) as rn
from email_track et1
)
select * from et2 where rn = 1;