I have a relational table where I need to loop through and sum amount values until a specified amount criteria is met. The data looks like this:
Company | Account | Amount |
---|---|---|
Coastal | A384 | 500 |
Coastal | C940 | 200 |
Coastal | Z934 | 200 |
American | U202 | 200 |
American | I034 | 300 |
Tester | P034 | 300 |
I want to have a function where I can loop through this data and specify an amount criteria that either returns 1 or more accounts once the threshold is met for each company. If the threshold is not met there should be some output that specifies the criteria was not met and the largest account value should be returned. I am thinking I would need to convert Account + Amount into an array to loop through. Pseudo code would look like:
var threshold = 500
var amount_total = 0
var array_result = {}
for each item in account_array
array_result(account: amount)
amount_total += amount
if amount_total = threshold
return array_result
My expected output from this would be:
Company | array_result | status |
---|---|---|
Coastal | {"A384": 500} | "Met Criteria" |
American | {"U202": 200, "I034": 300} | "Met Criteria" |
Tester | {"P034": 300} | "Did Not Meet Criteria" |
Ideally, I would be able to have this as as a function to be able to use in a select statement:
Select Company, find_accounts_that_meet_threshold(account_array_field, threshold) from company_table