SQL - 根据条件求和多行

时间:2016-12-15 11:13:13

标签: sql postgresql gaps-and-islands

我有一张像

这样的表格
id | value | date     | type
----------------------------
1  | 2     | 1.1.2016 | 1
----------------------------
2  | 6     | 2.1.2016 | 1
----------------------------
3  | 1     | 7.1.2016 | 1
----------------------------
4  | 10    | 3.1.2016 | 2
----------------------------
5  | 8     | 8.1.2016 | 1

我需要编写一个查询,它获取排列的类型1条目,使得它们之间没有类型2条目的条目在同一行上求和。在我的示例中,查询将返回

sum | start    | end
-------------------------
8   | 1.1.2016 | 2.1.2016
-------------------------
9   | 7.1.2016 | 8.1.2016

2 个答案:

答案 0 :(得分:1)

您可以通过计算行前非1值的数量来识别每个组。其余的只是聚合:

select sum(value), min(date), max(date)
from (select t.*,
             sum(case when type <> 1 then 1 else 0 end) over (order by id) as grp
      from t
     ) t
where type = 1
group by grp;

答案 1 :(得分:-1)

您可以尝试lead()功能,如下面的查询

select 
      value+lead_value as value, 
      date as start_date, 
      end_date
from(
    select *, 
           lead(value) over(order by id asc) lead_value, 
           lead(date) over(order by id asc) end_date, 
           ROW_NUMBER() over(partition by t order by id asc) row_num 
    from t1
    where type = 1)t2
where row_num % 2 = 1;

这给了我以下结果

enter image description here