Question

I have been trying to search for this and am not sure I am using the correct terms. Or it might just be that it's not possible. But what I am trying to do is update all records in a table that make up a sum value that is less than a set value.

So here is an example:

ID   type    amount   received_date    processed_date
1    debit   10       7/1/2010         NULL
2    debit   10       7/2/2010         NULL
3    debit   10       7/3/2010         NULL

Now what I want to do is update all records that are equal to a sum of less than 22. So when I would do the sum id 1 and 2 would equal 20 which is less than 22. But it also needs to be only records that have a null for processed_date. I also want it to work so that it updates from oldest to newest.

Basically here is how I would write it in pseudo code:

UPDATE credits
SET date_processed = '8/1/2010'
WHERE SUM(amount) <= @total AND
    credit_type = [debits]

But I know that this doesn't work. So I'm hoping some SQL master might have ideas.

I'm sure I could write this within a cursor but I'm wondering if there is a set based way to perform this.

EDIT: I updated the table and brief description below to better portray my circumstance.

Was it helpful?

Solution

Rows in a SQL table, represent an unordered list of items. Thus, we have to provide an order. In your example, you hint that it should process the rows ordered by Id.

Update TableName
Set processed_date = '2010-08-01'
Where [type] = 'debit'
    And Exists      (
                    Select 1
                    From TableName As C1
                    Where C1.Id <= TableName.Id
                        And C1.[type] = 'debit'
                    Having Sum(C1.amount) <= @total
                    )

As I mentioned in comments, it is not safe to depend on Id being the marker for sequence. It is possible to have gaps and for someone to insert "later" rows into those gaps using IDENTITY_INSERT. Instead, you should use a datetime column. If that column is received_date, then simply substitute Id for received_date in the above query.

OTHER TIPS

You should use the HAVING clause for this type of situations.

According to w3schools, "The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions."

UPDATE credits
SET date_processed = '8/1/2010'
WHERE credit_type = [debits]
HAVING SUM(amount) <= @total 

Here is a great tutorial found on w3schools

http://www.w3schools.com/SQL/sql_having.asp

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top