我有一张表格,其中包含以下详细信息
+------+---------+-------+--+
| name | Plan | Date | |
+------+---------+-------+--+
| A | free | 3/06 | |
| B | paid | 2/06 | |
| A | paid | 5/06 | |
| B | paid | 5/06 | |
+------+---------+-------+--+
我想找到今天已进入付费计划的人的列表。但前提是他们以前的计划也已付费
在这种情况下(今天的当前日期是5/06),我只会得到B(因为A的先前pla是免费计划)
在postgres中我有什么办法吗?
答案 0 :(得分:0)
您可以使用窗口功能查看上一行:
create table test (name text, plan text, date date);
insert into test values ('A', 'free', '2019-03-06'), ('B', 'paid', '2019-02-06'), ('A', 'paid', '2019-05-06'), ('B', 'paid', '2019-05-06');
select name
FROM
(select name,
date,
plan = lag(plan) over (partition by name order by date) as same_as_prev
FROM test
WHERE plan = 'paid'
) sub
WHERE date = '2019-05-06'
AND same_as_prev = 't';
name
------
B
(1 row)
编辑:我刚刚意识到我可能将您的月份和日期混在一起了,但是想法是完全一样的
答案 1 :(得分:0)
您可以使用EXISTS
来做到这一点:
select t.*
from test t
where t.date = current_date and plan = 'paid'
and exists (
select 1 from test
where
name = t.name and plan = 'paid'
and date = (select max(date) from test where name = t.name and date < t.date)
)