Question

Ok, I'm looking for a way to make a certain field be equal to the sum of 3 other fields. I have 3 different rating fields, and then an 'overall rating' field, which I need to be automatically equal the sum of the other 3. I know how to retrieve the value using a select statement, I just want it to happen automatically in the table. -Using MySQL

Was it helpful?

Solution

There are different ways to do this in different DBMSes, for example Virtual Columns,

in Oracle:

overall NUMBER GENERATED ALWAYS AS (rating1 + rating2 + rating3) VIRTUAL

in SQL Server:

[overall] AS (rating1 + rating2 + rating3) PERSISTED

Unfortunatelly not all DBMSes support virtual columns. The most generic (working on most DBMSes) way to do this, and yet probably the best for your needs (no database structural change needed) is creating a view, for example like:

CREATE VIEW ratings_overall AS 
   SELECT rating1, rating2, rating3, (rating1 + rating2 + rating3) as overall
   FROM source_table;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top