Using PostgreSQL 9.1.3 I have a points
table like so (What's the right way to show tables here??)
| Column | Type | Table Modifiers | Storage
|--------|-------------------|-----------------------------------------------------|----------|
| id | integer | not null default nextval('points_id_seq'::regclass) | plain |
| name | character varying | not null | extended |
| abbrev | character varying | not null | extended |
| amount | real | not null | plain |
In another table, orders
I have a bunch of columns where the name of the column exists in the points
table via the abbrev column, as well as a total_points
column
| Column | Type | Table Modifiers |
|--------------|--------|--------------------|
| ud | real | not null default 0 |
| sw | real | not null default 0 |
| prrv | real | not null default 0 |
| total_points | real | default 0 |
So in orders
I have the sw
column, and in points
I'll now have an amount
that realtes to the column where abbrev
= sw
I have about 15 columns like that in the points
table, and now I want to set a trigger so that when I create/update an entry in the points
table, I calculate a total score. Basically with just those three shown I could do it long-hand like this:
UPDATE points
SET total_points =
ud * (SELECT amount FROM points WHERE abbrev = 'ud') +
sw * (SELECT amount FROM points WHERE abbrev = 'sw') +
prrv * (SELECT amount FROM points WHERE abbrev = 'prrv')
WHERE ....
But that's just plain ugly and repetative, and like I said there are really 15 of them (right now...). I'm hoping there's a more sophisticated way to handle this.
In general each of those silly names on the orders
table represents a type of work associated with the order, and each of those types has a 'cost' to it, which is stores in the points
table. I'm not married to this structure if there's a cleaner setup.