1
[Raw data]
A  B    C 
1  10   1 
1  10   2
2  20   3
2  20   4
1  100  5
1  100  6

[Wanted result]
A    SUM_OF_B
1    20
2    40
1    200

It's unuseful that the query has the simple 'group by' clause and 'dense_rank over partition by' because grouping works all rows. However I want grouping in state of ordering. How do I write the proper query?

shA.t
  • 16,580
  • 5
  • 54
  • 111
wiz
  • 43
  • 7
  • 2
    Also, what is the ordering based on? Are you assuming that the raw data already comes in a certain order (bad idea)? Or do you sort by column B? – sstan Jul 14 '15 at 00:48
  • @sstan thank you. I modified the question. Adding column C. – wiz Jul 14 '15 at 00:56
  • Not an Oracle wizard, but this should be an acceptableish adaptation of the linked answer: http://www.sqlfiddle.com/#!4/58dcd/16 – Amadan Jul 14 '15 at 01:12
  • @Amadan thank you but your query doesn't work on my oracle. – wiz Jul 14 '15 at 01:45

1 Answers1

5

You need to identify the groups of adjacent records. You can actually do this by using a difference of row numbers approach -- assuming that c orders the rows. The difference is constant for consecutive values of a that are the same:

select a, sum(b)
from (select t.*,
             (row_number() over (order by c) -
              row_number() over (partition by a order by c)
             ) as grp
      from table t
     ) t
group by grp, a
order by min(c);
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786