Ask the Expert

A scalar subquery

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.

    Requires Free Membership to View

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


This was first published in March 2004

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: