in reply to Perl solution for SQL problem?
What you're looking for is a trigger. In Oracle, I would write it something like:
(The ending slash is important, for Oracle. YMMV)CREATE TRIGGER TRG_SUM_PERSONCOUNT AFTER INSERT OR UPDATE OR DELETE ON CASES BEGIN UPDATE geo_m_count g SET person_count = ( SELECT COUNT(*) FROM cases c WHERE g.oacode LIKE c.oacode AND g.sex = c.sex AND c.ageyears BETWEEN g.age_start and g.age_end ) END; /
Basically, what that does is whenever any of the rows in CASES changes, person_count is updated in all rows in GEO_M_COUNT. Now, this can be very inefficient, if you are doing more changes than selects. You might want to consider changing how you are viewing your data. Without knowing much, I am going to hazard a guess that you're doing some sort of statistical analysis of death information. Based on that, I would recommend looking at things differently. I'd have the following tables:
In every base table, there is an ID field. This is a database unique identifier, assigned when the row is inserted. It has nothing to do with the data, other than to identify a given row.
Your other table (Geo_m_count) is a summary table. It doesn't hold data - it organizes it. So, you could do a view (materialized or not - your choice). Look up how views are done in MS-SQL. (I've never really used it, being an Oracle person.) But, your basic select statement could look like:
SELECT cause_of_death ,oa_code ,gender ,MIN( date_death - date_birth ) AS age_start ,MAX( date_death - date_birth ) AS age_end ,COUNT( * ) FROM cases GROUP BY cause_of_death ,oa_code ,gender ;
A few thoughts on your SQL in general.
------
We are the carpenters and bricklayers of the Information Age.
Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.
|
|---|