2016-12-15 68 views
0

我有一个像SQL - 和基于状态

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 
+5

你有什么迄今所做.. –

+0

我不明白你的例子。它不应该是'9,'1.1.2016','7.1.2016'和'8,'8.1.2016','8.1.2016'吗? – pozs

+0

他希望通过日期范围,而不是id。 – BinaryPatrick

回答

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; 
+0

这是一个非常优雅的方式来做到这一点,它也确实表现出色。虽然要得到所要求的分组,但我认为它需要按照如下日期: 'SUM(Case when when type = 1 then 0 else 1 END)OVER(ORDER BY Date)Grp' 我也颠倒了案例逻辑,因为我认为它读得更干净。 – BinaryPatrick

-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

+0

对于大集合,使用这种许多窗口函数并不那么高效。 – BinaryPatrick