oracle - SQL Grouping by Ranges -
i have data set has timestamped entries on various sets of groups.
timestamp -- group -- value --------------------------- 1 -- -- 10 2 -- -- 20 3 -- b -- 15 4 -- b -- 25 5 -- c -- 5 6 -- -- 5 7 -- -- 10
i want sum these values group
field, parsed appears in data. example, above data result in following output:
group -- sum -- 30 b -- 40 c -- 5 -- 15
i not want this, i've been able come on own far:
group -- sum -- 45 b -- 40 c -- 5
using oracle 11g, i've hobbled togther far. know wrong, i'm hoping i'm @ least on right track rank()
. in real data, entries same group 2 timestamps apart, or 100; there 1 entry in group, or 100 consecutive. not matter, need them separated.
with sub_q (select k_id , grp , val -- rank timestamp separate groups same name , rank() over(partition k_id order tmstamp) rnk my_table k_id = 123) select t1.k_id , t1.grp , sum(case when t1.grp = t2.grp t1.val else 0 end) total_value sub_q t1 -- main value inner join sub_q t2 -- timstamp after on t1.k_id = t2.k_id , t1.rnk = t2.rnk - 1 group t1.k_id , t1.grp
is possible group in way? how go doing this?
i approach problem defining group different of 2 row_number()
:
select group, sum(value) (select t.*, (row_number() on (order timestamp) - row_number() on (partition group order timestamp) ) grp my_table t ) t group group, grp order min(timestamp);
the difference of 2 row numbers constant adjacent values.
Comments
Post a Comment