Skip to content
Advertisement

Get Sum(Column) over (partition by other columns) with subset of partition

I need to make a sum of the count of all items in “count2” for the partitions, the screenshot below shows better than I could explain, but I need to sum the items in that column and then subtract them form the “Lead2” column I have the following query:

which returns this table:

The table is ordered by date/race number and event_id. this should be the final order of the table.

What I’m needing is to sum the count of every row in count2 within the range between the count1 items.

It might be easier to understand with graphic (click to enlarge).

enter image description here

So basically what I need to do is to summarize what is on the blue boxes and then subtract it to the not null row from lead2 and add into countlead2. I can even handled it with temporal table or create a new column where to insert, so it can be cleaner and calculated later. but I don’t know how to summarize the count of the blue box.

I’ve tried with combinations of grouping sets, and different combinations of sum over partitions. but I can’t seem to be able to do what I need. I think partition by is the way to go.

So far I’ve tried with the 1 following and unbounded following to try to get the data I want, but it seems to go out of bounds. Is there a way to get the bound to be a variable? or to select the last following as the first of the next? And it seems that the preceding/following is not working with the partition I need.

Advertisement

Answer

One way is to do it in multiple stages, rather than trying to do it all in a single SELECT statement.

If you know better ways to identify which rows to SUM(), you may be able to shorten this. I just went with the most obvious rules based on your sample data.


EDIT:

To demonstrate what Common Table Expressions are, this is what the above code would look like with old-school nested sub-queries…

Most people, once they get used to CTEs, find them much easier to read, modify and debug.

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