数据库是HP Vertica的7或PostgreSQL 9如何将SQL连接重写到窗口函数中?
create table test (
id int,
card_id int,
tran_dt date,
amount int
);
insert into test values (1, 1, '2017-07-06', 10);
insert into test values (2, 1, '2017-06-01', 20);
insert into test values (3, 1, '2017-05-01', 30);
insert into test values (4, 1, '2017-04-01', 40);
insert into test values (5, 2, '2017-07-04', 10);
在最近一天使用的支付卡,什么是在最近90天内收取该卡上的最大金额。
select t.card_id, max(t2.amount) max
from test t
join test t2 on t2.card_id=t.card_id and t2.tran_dt>='2017-04-06'
where t.tran_dt>='2017-07-06'
group by t.card_id
order by t.card_id;
结果是正确的
card_id max
------- ---
1 30
我想重写查询到SQL窗口功能。
select card_id, max(amount) over(partition by card_id order by tran_dt range between '60 days' preceding and current row) max
from test
where card_id in (select card_id from test where tran_dt>='2017-07-06')
order by card_id;
但结果集不匹配,这怎么办?
测试数据在这里: http://sqlfiddle.com/#!17/db317/1
首先,Postgres的和Vertica的是两个完全不同的事情。其次,你为什么期望两个截然不同的查询结果是相同的? – mustaccio