基于SQL中的有序列聚合行

时间:2015-09-01 01:43:14

标签: sql postgresql

我有一个按名称列出有序列的表,来自:

Name   from   to   code
name1   0      1    cal
name1   1      2    cal/top
name1   2      4    cal
name1   4      5    top
name1   5      6    cal
name2   0      3    top
name2   3      5    cal
name2   5      7    cal/top

我希望根据 CAL

等代码将它们聚合到一个表中
Name    minFrom   MaxTo  
name1    0         4
name1    5         6
name2    3         7

我试过这个:

SELECT name, MIN(from) AS minfrom, MAX(to) AS maxto
FROM table1
GROUP BY name, code, From
HAVING code like "*CAL*"
ORDER BY name,  From;

并在stackoverflow上搜索了一个没有运气的问题。我想我必须做一个选择子查询,但我不知道从哪里开始...请帮忙!顺便说一句,我正在使用postgresql ...

2 个答案:

答案 0 :(得分:1)

您可以使用行号的差异来识别类似记录的组。这为您提供了一个分组列,然后可以将其用于聚合:

select name, min(from) as minfrom, max(to) as maxto
from (select t.*,
             (row_number() over (partition by name order by from) -
              row_number() over (partition by name,
                                              (case when code like 'col%' then 1 else 0 end)
                                 order by from
                                )
             ) as grp
      from table1 t
     ) t
where code not like 'col%' 
group by grp, name;

答案 1 :(得分:0)

您是否能够在不需要分区表的情况下重现?我认为放弃你的声明可能对where语句有意义。

SELECT name, MIN(from) AS minfrom, MAX(to) AS maxto
FROM table1
Where code like "*CAL*"
GROUP BY name, code, From
ORDER BY name,  From;