Make a Query With a Calculated Field

From Apache OpenOffice Wiki
Jump to: navigation, search




Make a Query With a Calculated Field

Imagine you would like to calculate a commission for each sale that is 7% of the sale amount. The process is just like the last query except that at step 3 an additional column is added manually to the query description, as shown in Figure 195. Notice the fourth column where the Field is defined as "Amount" * 0.07. The name of the column upon which the calculation is based should be enclosed in double quotes. Besides the usual arithmetical operators of +, -, *, and /, many other functions such as square root (sqrt) and the trigonometric functions are available. The calculations may also use more than one column, so you could, for example, calculate the difference or ratio of two columns.

Some other details to note in the calculated column are that it has the text Commission written in its Alias row, and that the Table row is blank. These changes should make sense. The column is not stored in a table, and therefore it does not have a good default name. If the alias is not supplied, the text of the calculation is used, which is not often a helpful column header. Note also that the criterion in the Amount column has been removed. This was not required; it is perfectly possible to do the calculation only on rows that meet any number of criteria.

An important point in database design is that calculations based on field values should be done in queries and not stored in the regular database tables. The main reason for this is that if the underlying values are updated, the calculated values in a regular table will not be automatically updated. You have to explicitly recalculate them. In a query, on the other hand, only the code to run the query is stored, so any calculated values are updated every time the query is run.

AOO41GS8 036.png
Figure 195: A query with a calculated field
Content on this page is licensed under the Creative Common Attribution 3.0 license (CC-BY).
Personal tools