Skip to content
Advertisement

How to sum rows in groups of 3?

I have a table that looks like this:

I need a query that returns the summed amount of rows grouped by every 3 consequent IDs. The result should be:

In my table, you can assume IDs are always consequent. So there can’t be a 10 without existing a 9 too. But the same ID can also show up multiple times with different amounts (just like in my example above).

Advertisement

Answer

Assuming ID is a numeric data type. Demo

Giving us:

Doc Link: Ceiling

  • MaxID is included just so the order by makes sense and validation of totals can occur.
  • I used 3.0 instead of 3 and implicit casting to a decimal data type (a hack I know but it works) otherwise integer math takes place and the rounding when the division occurs provides a incorrect result.

Without the .0 on the 3.0 divisor we’d get:

Ceiling() is used over floor() since floor() would not allow aggregation of 1-3 in the same set.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement