Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何在红移中执行此查询?_Sql_Amazon Redshift - Fatal编程技术网

Sql 如何在红移中执行此查询?

Sql 如何在红移中执行此查询?,sql,amazon-redshift,Sql,Amazon Redshift,对于每个site\u id,我必须确定plan\u id是否在过去是1(过去表示较小的id),并且在此之前的某个点不是1,例如: 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,

对于每个
site\u id
,我必须确定
plan\u id
是否在过去是
1
(过去表示较小的
id
),并且在此之前的某个点不是
1
,例如:

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
给定的
站点id
计费记录数可以是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

还有别的办法吗?Redshift与Postgres类似,因此Postgres也可能对此给出答案。

我找到了连接的解决方案:

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
选择b1.site\u id,min(b3.id)
来自账单b1
左连接计费b2打开(b2.id
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