SQL - 根据条件求和到多行
SQL - sum to multiple rows based on condition
我有一个table喜欢
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 类条目的条目汇总到同一行。在我的示例中,查询将 return
sum | start | end
-------------------------
8 | 1.1.2016 | 2.1.2016
-------------------------
9 | 7.1.2016 | 8.1.2016
您可以通过计算行前非 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;
您可以尝试 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;
这给了我以下结果
我有一个table喜欢
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 类条目的条目汇总到同一行。在我的示例中,查询将 return
sum | start | end
-------------------------
8 | 1.1.2016 | 2.1.2016
-------------------------
9 | 7.1.2016 | 8.1.2016
您可以通过计算行前非 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;
您可以尝试 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;
这给了我以下结果