Skip to content
Advertisement

SQL Combining MAX and SUM

So I have one SQL table that contains the below columns:

There are ~2800 unique License numbers and will have numerous FundsIn each day. I am trying to find the last date there was activity (ActivityDate) and the sum of all of the FundsIn on that MAX ActivityDate.

Below is a query I’ve been trying to modify to get it to work, but it is returning the sum of the license number across all dates and not just the MAX date.

I know the issue with the current query is that it is grouping the entire dataset of FundsIn, but I can’t figure out how to limit the sum of FundsIn to only the MAX date. Any help would be appreciated.

Sample Date

In the above data the query would return the below

Advertisement

Answer

I understand that you want the sum of the funds on the latest activity date per license (not all licenses might be active every day).

There are multiple ways to phrase this. One method is a filter with a correlated subquery:

Out of other options, a more exotic alternative is order by and top (1) with ties:

I would expect the second method to be less efficient on a large dataset.

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