I have a table that holds course marks. There are two different types of marks, the coursework mark and the exam mark. I want to make a double calculation. First, calculate the sum of 25% of coursework mark and 75% of exam mark, divide by 2 and store in a new column called Result. Then, calculate the sum of Result then divide by 10 (as there are 10 topics in the course) and store the final result in a new colunm called FinalAverage.
Seems pretty straightforward. Try this:
select topic , ( coursework + 3 * exam ) / 8 as result from marks
This will return the result for each topic. Notice that it's a SELECT query, producing data in two columns: topic and result.The data is not actually saved anywhere in the database, because of an important rule of thumb in database design: do not store derived data.
Storing derived data immediately introduces the risk, the possibility, indeed some would say the probability, of inconsistent data.
Also, note that the calculation is "A plus 3B divided by 8" rather than "0.25A plus 0.75B divided by 2" because three arithmetic operations is more efficient than four. If you need a decimal result, divide by 8.00 instead.
For the second part of your requirements, try this:
select ( sum(coursework) + 3 * sum(exam) ) / ( 8 * (select count(distinct topic) from marks) ) as finalaverage from marks
This query combines the result calculation with an averaging operation. Note that you let the query decide how many topics there are, using a scalar subquery. A scalar subquery produces one value, and can be calculated by the database optimizer before executing the outer query.
Also, note that the calculation is "(sum(A) plus 3sum(B)) divided by 8N" rather than "sum(0.25A plus 0.75B) divided by 2N" because 2N+2 operations is more efficient than 4N+2.
For More Information
- Dozens more answers to tough SQL questions from Rudy Limeback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, SQL Server, DB2, object-oriented and data warehousing gurus are waiting to answer your toughest questions.