Q

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...

.

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

Dig deeper on Oracle and SQL

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

0 comments

Oldest 

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:

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close