2017-03-03 163 views
0

對於每個site_id我有,以確定是否plan_id在過去1(過去就意味着較小id1在此之前的一些點,例如:如何在Redshift中執行此查詢?

create table billing (id int, site_id int, plan_id int); 

insert into billing values 
(40301, 1, 1), (40302, 1, 16), (40304, 1, 15), 
(40401, 2, 1), (40402, 2, 16), (40403, 2, 1), (40404, 2, 15); 

應返回:

site_id = 1, did_return = false 
site_id = 2, did_return = true 

給定site_idbilling記錄的數量可能爲1或幾十。

我曾嘗試嵌套查詢:

select (
    select (
     select id from billing where plan_id <> 1 and id < b2.id order by id desc limit 1 
    ) 
    from billing b2 where plan_id = 1 and id < b1.id order by id desc limit 1 
) 
from billing b1 
order by id desc limit 1 

但紅移不支持這種類型的查詢:

ERROR: This type of correlated subquery pattern is not supported due to internal error 

是否有另一種方式做到這一點? Redshift與Postgres類似,因此也可能有postgres的答案。

回答

1

我找到了解決辦法與聯接:

select b1.site_id, min(b3.id) 
from billing b1 
left join billing b2 on (b2.id < b1.id and b1.site_id = b2.site_id and b2.plan_id = 1) 
left join billing b3 on (b3.id < b2.id and b2.site_id = b3.site_id and b3.plan_id <> 1) 
group by b1.site_id