Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.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_Postgresql_Window Functions_Gaps And Islands - Fatal编程技术网

Sql 使用指定的顺序,按字段选择连续分组

Sql 使用指定的顺序,按字段选择连续分组,sql,postgresql,window-functions,gaps-and-islands,Sql,Postgresql,Window Functions,Gaps And Islands,我需要帮助解决以下任务,其中我需要使用窗口函数。但我不知道如何从子查询示例中获取id,以便对聚合函数进行排序和应用: 给定表格: create temp table users(id bigserial, group_id bigint); insert into users(group_id) values (1), (1), (1), (2), (1), (3); 在此表中,按ID排序,您需要: 要在组id上分配连续组,请考虑 指定的行顺序组有4行 计算每组中的记录数 计算组中的最小记录I

我需要帮助解决以下任务,其中我需要使用窗口函数。但我不知道如何从子查询示例中获取id,以便对聚合函数进行排序和应用:

给定表格:

create temp table users(id bigserial, group_id bigint);
insert into users(group_id)
values (1), (1), (1), (2), (1), (3);
在此表中,按ID排序,您需要: 要在组id上分配连续组,请考虑

指定的行顺序组有4行

计算每组中的记录数

计算组中的最小记录ID

结果应该是:

其中一列是组id,另一列是记录数或最小id值,具体取决于任务。行应按id排序

输出如下:

 group_id | count
----------+-------
        1 |     3
        2 |     1
        1 |     1
        3 |     1
第二个任务的部分解决方案,无需排序:

SELECT COUNT(*), group_id
FROM ( SELECT id, id - ROW_NUMBER() OVER (PARTITION BY group_id ORDER 
BY id) AS res, group_id FROM users)new_table
GROUP BY group_id,res;
这将返回:

 group_id | count 
----------+-------
        1 |     3
        3 |     1
        1 |     1
        2 |     1

我猜这就是你想要的:

SELECT group_id
     , count(*) AS row_count  -- 2. count the number of records in each group
     , min(id)  AS min_id     -- 3. calculate the minimum record ID in the group
FROM  (
   SELECT id
        , group_id
        , id - row_number() OVER (PARTITION BY group_id ORDER BY id) AS res
   FROM   users
   ) sub
GROUP  BY group_id, res
ORDER  BY min_id;  -- 1. specified order of rows group
当然,如果序列列id中可能存在间隙,则必须使用:

  row_number() OVER (ORDER BY id)
- row_number() OVER (PARTITION BY group_id ORDER BY id) AS res
通常情况下,必须预计序列列中存在间隙

提供更多解释和链接的相关答案:


编辑您的问题并显示应生成的结果。考虑到指定的记录顺序,共有4条记录?显然有4条以上的记录,考虑到这些记录并不能定义任何内容。请用有意义的方式描述你的目标。对于这个例子,你也没有给出期望的结果。那么你有你的答案吗?