I’m making a walkathon rails app. Each walker is sponsored by people who pledge money per lap up to a maximum amount.
I have a table called sponsorships that has columns walker_id, amount_per_lap, and max_amount. I want to write a SQL query to determine how much money a walker has raised.
There is also a walkers table that has id, name, and laps columns.
I know this isn’t valid SQL, but I wanted something like this, but don’t know the best way to do it. The walker_id and laps could be provided before executing the query.
SELECT SUM(MIN(Laps * sponsorships.amount_per_lap, sponsorships.max_amount)) FROM sponsorships
where sponsorships.walker_id = 1;
I’m making this in rails, so I was trying to figure out how to do something like this in Arel, but couldn’t figure it out.
Any help would be greatly appreciated.
Edit: clarifying the walkers table.
Edit2: Accidentally had max instead of min in the pseudo code
I think the SQL you’re looking for is this:
The
leastfunction is what applies your “no more thanmax_amount” condition. Translating that to AR should be a simple matter for you now that you know what to SELECT; I tend to go straight to SQL for anything like this.